C#中的解析器。如何从字符串填充类

C#中的解析器。如何从字符串填充类,c#,class,parsing,C#,Class,Parsing,我试图做一个简单的解析器,它接收一个数组并返回一个包含填充成员的类 我有下面的类实现下面的接口 public class ReturnedObject : IReturnedObject { public string Source { get; set; } public string Destination { get; set; } } public interface IReturnedObject { string So

我试图做一个简单的解析器,它接收一个数组并返回一个包含填充成员的类

我有下面的类实现下面的接口

    public class ReturnedObject : IReturnedObject
{
        public string Source { get; set; }
        public string Destination { get; set; }
}

    public interface IReturnedObject
{
        string Source { get; set; }
        string Destination { get; set; }
}
例如,如果我收到以下行:

  • 命令-源值1-目标值2
我希望能够关联源值和目标值

主要方法如下所示:

        private static IReturnedObject Parse<T>(string[] userArgs, ICommandesUtils commandUtils) where T : IReturnedObject, new()
    {
    //userArgs contains the folling array
    //command
    //-source
    //value1
    //-destination
    //value2

    //some work...

    IReturnedObject returnedObject = new T();

    returnedObject.Source = userArgs[2];
    returnedObject.Destination = userArgs[4];   
    }
我想做一些类似的事情:

Dictionary<string, string> args; // Key = Property Name -- Value = Property Value
  • 对于类returnedObject的每个成员
  • 查看成员的名称(例如,“目的地”)
  • 在userArgs中找到要关联的良好值(本例中“-destination”后面的值)
  • 关联该值
  • 可能吗? 提前感谢:)

    您可以使用它

    首先,您应该以更好的方式存储参数。使用一个

    比如:

    Dictionary<string, string> args; // Key = Property Name -- Value = Property Value
    
    可以编辑值和逻辑以支持任何值类型。

    尝试Go Commando-

    代码:

    然后跑

    stuff.exe do-stuff -source ketchup -destination italy
    

    我怀疑这是针对控制台应用程序的?如果是这样,您是否考虑过:您的步骤看起来很有意义。基本上有三件事-迭代属性、查找值和设置值。您是否对所有三个部分都有问题,或者只是检查
    返回对象的位有问题?基本上,从args中找到正确的值似乎与设置值完全不同,所以我只是检查您是否正确……这是一个控制台应用程序将使用的类库。我不想用外包装。这个想法是让我自己:)。是的,问题是这三个部分。Clay07g用反思回答了我的问题。这正是我想要的。Thx:)Thx,但我不想使用外部软件包。我应该说明这一点。
    
    Install-Package GoCommando
    
    class Program
    {
        static void Main()
        {
            Go.Run();
        }
    }
    
    [Command("do-stuff")]
    [Description("I've no idea what we're doing")]
    public class WhiteRussian : ICommand
    {
        [Parameter("Source")]
        public double Source { get; set; }
    
        [Parameter("Destination")]
        public double Destination { get; set; }
    
        public void Run()
        {
            // Do stuff with Source and Destination.
        }
    }
    
    stuff.exe do-stuff -source ketchup -destination italy