gpt4 book ai didi

c# - 使用 C# 反射从字典生成动态对象

转载 作者:太空狗 更新时间:2023-10-29 20:52:57 25 4
gpt4 key购买 nike

我一直在研究 C# 中的反射,想知道我是否使用带有键值的字典可以创建一个对象,该对象的变量包含字典中每个键的名称及其值,该字典的键值。

我有一个相反的方法,从字典中提取一个对象,这个字典包含键和类属性及其值 ,属性的值。

如果可能,我想知道如何做到这一点。

下面是我的方法,它提取了一个对象的字典:

protected Dictionary<String, String> getObjectProperty(object objeto)
{
Dictionary<String, String> dictionary = new Dictionary<String, String>();

Type type = objeto.GetType();
FieldInfo[] field = type.GetFields();
PropertyInfo[] myPropertyInfo = type.GetProperties();

String value = null;

foreach (var propertyInfo in myPropertyInfo)
{
if (propertyInfo.GetIndexParameters().Length == 0)
{
value = (string)propertyInfo.GetValue(objeto, null);
value = value == null ? null : value;
dictionary.Add(propertyInfo.Name.ToString(), value);
}
}

return dictionary;
}

最佳答案

如果你已经有了字典,我会避免反射而只使用 DynamicObject

例如:

public class DynamicDictionary : DynamicObject
{
private readonly Dictionary<string, object> dictionary;

public DynamicDictionary(Dictionary<string, object> dictionary)
{
this.dictionary = dictionary;
}

public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
return dictionary.TryGetValue(binder.Name, out result);
}

public override bool TrySetMember(
SetMemberBinder binder, object value)
{
dictionary[binder.Name] = value;

return true;
}
}

可以按如下方式使用:

dynamic x = new DynamicDictionary(
new Dictionary<string, object> {{"Name", "Peter"}});

Console.WriteLine(x.Name);

关于c# - 使用 C# 反射从字典生成动态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18290852/

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