gpt4 book ai didi

c# - 将对象映射到字典,反之亦然

转载 作者:IT王子 更新时间:2023-10-29 03:40:15 25 4
gpt4 key购买 nike

有没有优雅快速的方法将对象映射到字典,反之亦然?

示例:

IDictionary<string,object> a = new Dictionary<string,object>();
a["Id"]=1;
a["Name"]="Ahmad";
// .....

成为

SomeClass b = new SomeClass();
b.Id=1;
b.Name="Ahmad";
// ..........

最佳答案

在两个扩展方法中使用一些反射和泛型,您可以实现这一点。

是的,其他人基本上采用了相同的解决方案,但这种方法使用的反射更少,性能更佳且可读性更强:

public static class ObjectExtensions
{
public static T ToObject<T>(this IDictionary<string, object> source)
where T : class, new()
{
var someObject = new T();
var someObjectType = someObject.GetType();

foreach (var item in source)
{
someObjectType
.GetProperty(item.Key)
.SetValue(someObject, item.Value, null);
}

return someObject;
}

public static IDictionary<string, object> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
{
return source.GetType().GetProperties(bindingAttr).ToDictionary
(
propInfo => propInfo.Name,
propInfo => propInfo.GetValue(source, null)
);

}
}

class A
{
public string Prop1
{
get;
set;
}

public int Prop2
{
get;
set;
}
}

class Program
{
static void Main(string[] args)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("Prop1", "hello world!");
dictionary.Add("Prop2", 3893);
A someObject = dictionary.ToObject<A>();

IDictionary<string, object> objectBackToDictionary = someObject.AsDictionary();
}
}

关于c# - 将对象映射到字典,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4943817/

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