Dictionary<TKey,object> 修改索引器以在返回值之前进行转换

Dictionary<TKey,object> modify indexer to cast before returning value

我在 question: :

中看到过这个

编辑: 类型在添加到字典之前是已知的

You could use Dictionary<string, object>, then you'd need to cast the results:

int no = 1;       
string str = "world";
Dictionary dict = new Dictionary<string,object>();

dict.add( "intObj" , no  );
dict.add( "intObj" , str );


int a = (int) Storage.Get("age"); //everthing was perfect till i see cast .
string b = (string) Storage.Get("name");
double c = (double) Storage.Get("bmi");

问题:如何修改方括号[]以在返回值之前转换类型 所以它看起来像这样;

int a = dict["intObject"] ;   //we got rid of casting forever
string b = dict["stringObject"] ;

谢谢。

(在提到 .NET 2.0 要求之前回答 - 它可能对其他人仍然有用。)

您可以改用 Dictionary<string, dynamic> - 此时表达式 dict["stringObject"] 的编译时类型将为 dynamic。对 string 类型变量的赋值将在执行时执行转换。

您无法更改 Dictionary<string, object> 的行为方式。您需要 来更改类型参数...不,您不能使用 .NET 2.0 执行此操作。

您不能直接修改索引器。您可以 做的是创建一个扩展方法来(部分)为您执行此操作:

public static class DictionaryExtensions
{
    public static T Get<T>(this Dictionary<string, object> dictionary, string key)
    {
        object value = null;
        return dictionary.TryGetValue(key, out value) ? (T)value : default(T);
    }
}

注意这有一些缩写:

  1. 如果有人插入带有 null 的键,如果该值是值类型,您将在运行时遇到强制转换异常。

  2. 如果值类型的值不存在,您将获得每个基元的默认值。请注意,这样您就无法真正指出字典中是否存在密钥。