我正在尝试将字典转换为接口的实现。
我可以得到一个对象的字典好吧。做这样的事情:
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)
);
}
}
var dictionary = new Dictionary<string, object> {{"Prop1", "hello world!"}, {"Prop2", 3893}};
var someObject = dictionary.ToObject<A>();
但我希望能够:
var someObject = dictionary.ToObject<iA>();
任何人都知道如何做到这一点?