如何将通用字典转换为已知类型?

Tim*_*Tim 2 c# reflection casting

使用反射,我试图抓住一个类字段并填充它们.目前我有它检测a的实例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]))
    });
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?谢谢.

use*_*301 9

你应该创建你找到的类型manualy字典.

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);
Run Code Online (Sandbox Code Playgroud)

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();
    }
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)