gpt4 book ai didi

c# - 从字典中填充一个类

转载 作者:太空狗 更新时间:2023-10-29 22:27:50 26 4
gpt4 key购买 nike

我有一个包含 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com