0
我試圖將字典轉換爲接口的插入。將字典轉換爲接口
我可以得到一個字典到一個對象好吧。做這樣的事情:
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>();
任何人都知道這可怎麼辦呢?
對於我來說寫一個沒有很好理由的'object'擴展方法看起來很糟糕。 –
你其實只是想做序列化?如果是這樣,則有更簡單的方法。例如。查找DataContractSerializer for XML或Json.NET for JSON。 –
如果您正在嘗試開發單元測試,您可能需要考慮使用像Moq這樣的現有模擬框架。這些框架已經支持創建實現接口的類,您可以輕鬆創建一個輔助方法,將字典轉換爲一系列Moq Setup調用。 –