使用反射,我試圖抓住一個類字段並填充它們。目前,我已經檢測到一個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]))
});
任何想法?謝謝。
你應該創建一個你找到的字典的通用實例,你不能使用你的一個。 – user854301