我有一个包含 100 多个字段和值的字典集合。有没有一种方法可以使用此集合来填充具有 100 个字段的巨大类?
此字典中的键对应于我的类的属性名称,值将是该类的属性值。
Dictionary<string, object> myDictionary = new Dictionary<string, object>();
myDictionary.Add("MyProperty1", "Hello World");
myDictionary.Add("MyProperty2", DateTime.Now);
myDictionary.Add("MyProperty3", true);
填充以下类的属性。
public class MyClass
{
public string MyProperty1 {get;set;}
public DateTime MyProperty2 {get;set;}
public bool MyProperty3 {get;set;}
}
最佳答案
您可以使用 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);
}
}
关于c# - 从字典中填充一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9167083/