2013-06-11 44 views
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>(); 

任何人都知道這可怎麼辦呢?

+1

對於我來說寫一個沒有很好理由的'object'擴展方法看起來很糟糕。 –

+0

你其實只是想做序列化?如果是這樣,則有更簡單的方法。例如。查找DataContractSerializer for XML或Json.NET for JSON。 –

+0

如果您正在嘗試開發單元測試,您可能需要考慮使用像Moq這樣的現有模擬框架。這些框架已經支持創建實現接口的類,您可以輕鬆創建一個輔助方法,將字典轉換爲一系列Moq Setup調用。 –

回答

1

您需要創建該接口的具體實現。你可以通過使用TypeBuilder class來做到這一點。

另外,您可以使用動態類型和Impromptu

using ImpromptuInterface; 
using ImpromptuInterface.Dynamic; 

public interface IMyInterface 
{ 
    string Prop1 { get; } 
} 

//Anonymous Class 
var anon = new { 
     Prop1 = "Test", 
} 

var myInterface = anon.ActLike<IMyInterface>(); 

我喜歡艾米的解決方案好了很多,雖然。上述兩者都要複雜得多,但是可以在不強制調用者指定實際的具體類型的情況下完成。

+0

我不知道Castle DynamicProxy(http://www.castleproject.org/projects/dynamicproxy/)是否可以完全適合,但我已將它用於類似用例,如mixins。 – Pragmateek