2011-12-22 132 views
2

我已經延長IDictionary的是這樣的:Howto調用方法擴展IDictionary(反射)?

public static T ToClass<T>(this IDictionary<string, string> source) where T : class, new() 
{ 
    T someObject = new T(); 

    foreach (KeyValuePair<string, string> item in source) 
    { 
     someObject.GetType().GetProperty(item.Key).SetValue(someObject, item.Value, null); 
    } 

    return someObject; 
} 

而且我使用的方法有問題,試着這樣說:

TestClass test = _rep.Test().ToClass<TestClass>; 

而且它說,它不能轉換到非委託類型。

調用它的正確方法是什麼?

/拉塞

  • UPDATE *

更改代碼:

public static T ToClass<T>(this IDictionary<string, string> source) where T : class, new() 
{ 
    Type type = typeof(T); 
    T ret = new T(); 

    foreach (var keyValue in source) 
    { 
     type.GetProperty(keyValue.Key).SetValue(ret, keyValue.Value, null); 
    } 

    return ret; 
} 

回答

5

你缺少結束括號:

TestClass test = _rep.Test().ToClass<TestClass>(); 

編譯器認爲您想將方法(委託)分配給該變量。


另外,代替someObject.GetType()你可以使用typeof(T),我會創建循環外的變量,並重新使用它了。

+0

非常感謝喬治,聖誕快樂:) – 2011-12-22 08:37:30