我正在尝试做一个简单的解析器,它接收一个数组并返回一个包含填充成员的类。
我有以下类实现以下接口(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];
我想做这样的事情:
- 对于返回对象类的每个成员
- 查看成员的名称(例如“目的地”)
- 在 userArgs 中找到要关联的良好值(在本例中为“-destination”之后的值)
- 关联值。
这可能吗? 提前谢谢你:)
最佳答案
您可以使用 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/