如果您坚持当前的设计(CSV + 字典),您可以使用 ExpandoObject 类来获取您要查找的内容,创建一个简单的工厂类:
public static class ObjectFactory
{
public static dynamic CreateInstance(Dictionary<string, string> objectFromFile)
{
dynamic instance = new ExpandoObject();
var instanceDict = (IDictionary<string, object>)instance;
foreach (var pair in objectFromFile)
{
instanceDict.Add(pair.Key, pair.Value);
}
return instance;
}
}
该工厂将创建您提供给它的任何字典的对象实例,即创建所有不同类型对象的一种方法。像这样使用它:
// Simulating load of dictionary from file
var actorFromFile = new Dictionary<string, string>();
actorFromFile.Add("Id", "1");
actorFromFile.Add("Age", "37");
actorFromFile.Add("Name", "Angelina Jolie");
// Instantiate dynamically
dynamic actor = ObjectFactory.CreateInstance(actorFromFile);
// Test using properties
Console.WriteLine("Actor.Id = " + actor.Id +
" Name = " + actor.Name +
" Age = " + actor.Age);
Console.ReadLine();
希望这会有所帮助。(是的,她出生于 1975 年)