为什么我不能将Type变量传递给c#中的关键字"default"?

Ev.*_*Ev. 1 c#

我是动态返回一个类型的默认值,但我不能将default关键字传递给Type类型的变量.

为什么不?

例如:

    private object GetSpecialDefaultValue(Type theType)
    {
        if (theType == typeof (string))
        {
            return String.Empty;
        }
        if (theType == typeof (int))
        {
            return 1;
        }
        return default(theType);
    }
Run Code Online (Sandbox Code Playgroud)

给我编译时错误:

找不到类型或命名空间名称'theType'(您是否缺少using指令或程序集引用?)

Mar*_*zek 5

您只能使用default泛型类型参数.

default关键字可以在使用switch语句或通用的代码:

默认(C#参考)

那一个怎么样?

private object GetSpecialDefaultValue<T>()
{
    var theType = typeof(T);

    if (theType == typeof (string))
    {
        return String.Empty;
    }
    if (theType == typeof (int))
    {
        return 1;
    }
    return default(T);
}
Run Code Online (Sandbox Code Playgroud)

更新

您可以尝试跟随而不是default,但我不是100%确定它会起作用.

return theType.IsValueType ? (object)(Activator.CreateInstance(theType)) : null;
Run Code Online (Sandbox Code Playgroud)