2012-08-23 144 views
2

使用反射,我試圖抓住一個類字段並填充它們。目前,我已經檢測到一個Dictionary<,>的實例並創建一個Dictionary<object,object>來填充。之後它嘗試改變類型,但是這不起作用並且失敗:如何將通用字典轉換爲其已知類型?

// Looping through properties. Info is this isntance. 
// Check is a dictionary field. 
Dictionary<object, object> newDictionary = new Dictionary<object, object>(); 

// Populating the dictionary here from file. 
Type[] args = info.PropertyType.GetGenericArguments(); 
info.GetSetMethod().Invoke(data, new object[] 
    { 
     newDictionary.ToDictionary(k => Convert.ChangeType(k.Key, args[0]), 
            k => Convert.ChangeType(k.Value, args[1])) 
    }); 

任何想法?謝謝。

+0

你應該創建一個你找到的字典的通用實例,你不能使用你的一個。 – user854301

回答

9

你應該創建你找到的類型的詞典。

Type dictionary = typeof(Dictionary<,>); 
Type[] typeArgs = info.PropertyType.GetGenericArguments(); 

// Construct the type Dictionary<T1, T2>. 
Type constructed = dictionary.MakeGenericType(typeArgs); 
IDictionary newDictionary = (IDictionary)Activator.CreateInstance(constructed); 

// Populating the dictionary here from file. insert only typed values below 
newDictionary.Add(new object(), new object()); 


info.SetValue(data, newDictionary, null); 

downvoters的證明。

static void Main(string[] args) 
    { 
     IDictionary<int, string> test = new Dictionary<int, string>(); 
     var castedDictionary = (IDictionary)test; 
     castedDictionary.Add(1, "hello"); 
     Console.Write(test.FirstOrDefault().Key); 
     Console.Write(test.FirstOrDefault().Value); 
     Console.ReadLine(); 
    } 

Dictionary<TKey, TValue>實現IDictionary,在我的例子進出口創造Dictionary<TKey, TValue>Type dictionary = typeof(Dictionary<,>);)實例。

public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, 
    ICollection<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, 
    IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, 
    IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, ISerializable, 
    IDeserializationCallback 
+0

如果以這種方式創建字典,那麼如何填充它?通過反射調用適當的「添加」方法? –

+0

simple newDictionary.Add(new object(),new object());您可以將值轉換爲其類型。 – user854301

+0

錯誤的答案! 'IDictionary '不會從'IDictionary'繼承。 –

-1

創建一個幫助通用類,會做任何你需要做的,產生鍵入正確的結果。然後根據運行時已知的類型動態地實例化該類。

interface IHelper 
{ 
    object CreateDictionary(); 
} 

class Helper<TKey, TValue> : IHelper 
{ 
    public object CreateDictionary() 
    { 
     return (whatever).ToDictionary<TKey, TValue>(blah); 
    } 
} 

var h = Activator.CreateInstance(typeof(Helper<,>).MakeGenericType(yourKnownKeyType, yourKnownValueType)) as IHelper; 
info.SetValue(h.CreateDictionary()); 

如果這種情況經常發生,您還應該緩存幫助程序實例以避免每次動態實例化的影響。

相關問題