从Dictionary中填充一个类

zSy*_*sis 5 .net c# reflection performance

我有一个超过100个字段和值的字典集合.有没有办法使用这个集合填充一个包含100个字段的巨大类?

此字典中的键对应于我的类的属性名称,值将是类的属性值.

Dictionary<string, object> myDictionary = new Dictionary<string, object>();
myDictionary.Add("MyProperty1", "Hello World");
myDictionary.Add("MyProperty2", DateTime.Now);
myDictionary.Add("MyProperty3", true);
Run Code Online (Sandbox Code Playgroud)

填充以下类的属性.

public class MyClass
{
   public string MyProperty1 {get;set;}
   public DateTime MyProperty2 {get;set;}
   public bool MyProperty3 {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*Wue 9

您可以使用GetProperties获取给定类型的属性列表,并SetValue用于为给定属性设置特定值:

MyClass myObj = new MyClass();
...
foreach (var pi in typeof(MyClass).GetProperties())
{
     object value;
     if (myDictionary.TryGetValue(pi.Name, out value)
     {
          pi.SetValue(myObj, value);
     }
}
Run Code Online (Sandbox Code Playgroud)