来源:Stackoverflow NET技术问答 https://mp.weixin.qq.com/s/hGlYLKcMf6DA2Zx0EkpHGg
咨询区是否有便捷的方式实现 object 和 dictionary 的互转,比如下面的例子: 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(); } }
可以参考开源的 Castle DictionaryAdapter 项目,地址:https://github.com/castleproject/Core/blob/master/docs/dictionaryadapter.md 它可以非常方便的实现 dict 和 object 之间的互转,你只需定义一个转换成 object 所实现的接口即可,参考如下代码: public interface IHelloWorld { string Message { get; } }
接下来为这个接口创建一个适配器,通过适配器就可以实现 dict 到 object 的转换了,参考如下代码: var dictionary = new Hashtable(); var factory = new DictionaryAdapterFactory(); var adapter = factory.GetAdapter<IHelloWorld>(dictionary); dictionary["Message"] = "Hello world!"; Debug.Assert(adapter.Message == "Hello world!");
下面是 object 到 dict 的转换。 adapter.Message = "Hello world!"; Debug.Assert(dictionary["Message"] == "Hello world!");
点评区这是一个在项目开发中经常会遇到的一个场景,我也是第一次知道 dict 和 object 之间的转换还可以通过DictionaryAdapter实现,学习了。 |