创建将类型T映射为类型T实例的键的字典

时间:2013-09-14 16:02:59

标签: c# collections dictionary

我想在该类型的类型和实例之间创建一个字典 例如,字典MyTypeDictionary:

Dictionary<Type,InstanceOfType> MyTypeDictionary = new  Dictionary<Type,InstanceOfType>();                        
MyTypeDictionary.Add(typeof(int),4);  
MyTypeDictionary.Add(typeof(string),"hello world");  
MyTypeDictionary.Add(typeof(DateTime),Datetime.Now); 
int MyInt = MyTypeDictionary[typeof(int)];

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:5)

我找到了办法。

我创建了一个包装字典的新类:

public class NewDictionary
{
    public Dictionary<Type, object> dic = new Dictionary<Type, object>();
    public void Add<T>(T obj)
    {
        dic[typeof(T)] = obj;
    }

    public T Get<T>()
    {
        if (IsTypeExists(typeof(T)) == false)
        {
            return default(T);
        }

        return (T)dic[typeof(T)];
    }

    public bool IsTypeExists(Type t)
    {
        if (dic.ContainsKey(t) == false)
            return false;
        else
            return true;
    }
}

通过使用这个类,我可以使用字典将类型映射到实例。 我可以这样使用它:

        NewDictionary myCollection = new NewDictionary();
        myCollection.Add<int>(4);
        myCollection.Add<string>("Hello world");
        myCollection.Add<DateTime>(DateTime.Now);

使用type:

通过'get'获取实例
        int number = myCollection.Get<int>();
        string text = myCollection.Get<string>();
        DateTime date = myCollection.Get<DateTime>();