如何使用value = null检查拆箱可空类型的类型?

时间:2013-03-25 09:53:39

标签: c#-4.0 nullable unboxing

看看这个方法:

Dictionary<string,object> ViewModelParams = new Dictionary<string,object>();

AddParam(string paramKey,value)
{
    viewModelParams.Add(paramKey,value);
}

T GetParam<T>(string paramKey)
{
    if(viewModelParams[paramKey] is T)
        return (T)viewModelParams[paramKey];
    else
        throw exception...
}

对于 Nullable ,将表达式if(viewModelParams[paramKey] is T)键入,如果字典中的值为null,则无法正常工作,以澄清:

int? item=null;
AddParam("key",item);
GetParam<int?>("key")// throw exception because of 
                     // (viewModelParams[paramKey] is T) is false

我知道可装空类型(Boxing Nullable Types)的装箱和拆箱概念,但我不知道在这种情况下用if(viewModelParams[paramKey] is T)替换了哪个表达式?

0 个答案:

没有答案