【问题标题】:Why can't I pass a Type variable to the keyword "default" in c#?为什么我不能将类型变量传递给 c# 中的关键字“default”?
【发布时间】:2014-02-24 14:02:26
【问题描述】:

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

为什么不呢?

例如:

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

给我编译时错误:

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

【问题讨论】:

标签: c#


【解决方案1】:

您只能将default 与泛型类型参数一起使用。

default 关键字可用于switch 语句或通用代码中:

来自default (C# Reference)

那个怎么样?

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

    if (theType == typeof (string))
    {
        return String.Empty;
    }
    if (theType == typeof (int))
    {
        return 1;
    }
    return default(T);
}

更新

您可以尝试关注而不是 default,但 我不能 100% 确定它会起作用

return theType.IsValueType ? (object)(Activator.CreateInstance(theType)) : null;

【讨论】:

  • +1。请注意,default(SomeType) 可以在任何地方使用,但在非泛型代码中没有多大意义,null/new SomeValueType 可以提供更多的清晰度。
  • 为了准确起见,我肯定会在您的帖子中记下 Alexi 的评论。
【解决方案2】:

default 不采用Type 的实例的原因是IL 中没有default 指令。 default 的语法根据类型是否为值类型转换为 ldnullinitobj T

如果您想从Type 获取默认值,请执行与给定in this other question 相同的逻辑:

public static object GetDefaultValue(Type t)
{
    if (!t.IsValueType || Nullable.GetUnderlyingType(t) != null)
        return null;

    return Activator.CreateInstance(t);
}

【讨论】:

    猜你喜欢
    • 2011-02-05
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多