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

标签 c# class parsing

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

我有以下类实现以下接口(interface)。

    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];   
    }

我正在寻找的是一种替换以下两行的方法:

returnedObject.Source = userArgs[2];
returnedObject.Destination = userArgs[4]; 

我想做这样的事情:

  1. 对于返回对象类的每个成员
  2. 查看成员的名称(例如“目的地”)
  3. 在 userArgs 中找到要关联的良好值(在本例中为“-destination”之后的值)
  4. 关联值。

这可能吗? 提前谢谢你:)

最佳答案

您可以使用 Reflection为此。

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

类似于:

Dictionary<string, string> args; // Key = Property Name -- Value = Property Value

然后,根据您的逻辑,执行:

PropertyInfo[] props = T.GetType().GetProperties();

foreach(var prop in props)
{
    string propName = prop.GetMethod.Name;

    if (args.ContainsKey(propName))
    {
        prop.SetValue(returnedObject, args[propName]);
    }
}

可以编辑值和逻辑以支持任何值类型。

关于c# - C# 中的解析器。如何从字符串填充类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47313143/

相关文章:

c# - 通过代码添加应用栏(Windows 8.1,C#)

c++ - C++中是否可以在另一个类的构造函数中声明一个类的对象?

python - Python 中的线程 : class attribute (list) not thread-safe?

python - 在 Python 中定义类方法的多种方法?

regex - 解析 Apache 错误日志以查找唯一错误

c - 使用 strtok() 从字符串中解析标记

c# - ASP.NET 5 (vNext) 中的身份验证

c# - 实现 IList 接口(interface)

c# - 如何向 C# 图表添加两个不同类型的系列?

java - 解析任务列表