【发布时间】:2011-09-19 10:22:08
【问题描述】:
我正在编写一个 ConfigParser 类,它从如下结构的配置文件中读取:
[Section]
option1 = foo
option2 = 12
option3 = ;
...
读取的信息实际上存储在 Dictionary
struct ConfigStruct
{
public string option1;
public int option2;
public char option3 { get; set; }
// Any other _public_ fields or properties
}
ConfigParser Cp = new ConfigParser("path/to/config/file"); // Loads content
ConfigStruct Cs = Cp.CreateInstance<ConfigStruct>("Section");
Console.WriteLine(Cs.option1); // foo
Console.WriteLine(Cs.option2.ToString()); // 12
Console.WriteLine(Cs.option3.ToString()); // ;
结构体(或类,没关系)ConfigStruct 是特定于应用程序的,ConfigParser 类应该对此一无所知。基本上,我想解析来自特定选项的值,并将其存储到具有相同名称的字段/属性中。应根据字段/属性类型进行解析。
我已经为它开发了一个存根方法:
public T CreateInstance<T>(string Section) where T : new()
{
// Gets options dictionary from loaded data
Dictionary<string, string> Options = this.Data[Section];
T Result = new T();
Type StructType = Result.GetType();
foreach (var Field in StructType.GetFields())
{
if (!Options.ContainsKey(Field.Name))
continue;
Object Value;
if (Field.FieldType == typeof(bool))
Value = Boolean.Parse(Options[Field.Name]);
else if (Field.FieldType == typeof(int))
Value = Int32.Parse(Options[Field.Name]);
else if (Field.FieldType == typeof(double))
Value = Double.Parse(Options[Field.Name]);
else if (Field.FieldType == typeof(string))
Value = Options[Field.Name];
else if (Field.FieldType == typeof(char))
Value = Options[Field.Name][0];
// Add any ifs if needed
else { /* Handle unsupported types */ }
Field.SetValue(Result, Value);
}
foreach (var Property in StructType.GetProperties())
{
// Do the same thing with public properties
}
return Result;
}
- 您认为这是解决问题的正确方法吗?或者我应该将初始化结构的责任转移到应用程序逻辑而不是 ConfigParser 类?我知道它更有效,但是使用反射我只编写了一次这个方法,并且适用于每个结构。
- 是否应该使用反射来调用 Parse() 以便避免所有这些 if?或者您更愿意逐个类型地进行这些转换,以防止出现意外行为?
感谢您的宝贵时间。
【问题讨论】:
标签: c# reflection