13
class MyClass
{
    public void MyMethod(Type targetType = typeof(MyClass))
    {
    }
}

不是typeof(MyClass)编译时常量吗?

4

5 回答 5

11

我不是 IL 专家,但似乎它在 L_0005 处调用了一个方法:

return typeof(int);

它与以下内容相同:

.maxstack 1
.locals init (
    [0] class [mscorlib]System.Type typeofvar)
L_0000: ldtoken int32
L_0005: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
L_000a: stloc.0 
L_000b: ldloc.0 
L_000c: ret 

您可以看到它不是恒定编写类型的代码:

const Type constType = typeof(int);

这会返回一个错误:

Constant initialize must be compile-time constant
于 2012-01-20T09:57:12.097 回答
5

来自 MSDN -命名和可选参数

默认值必须是以下表达式类型之一:

  • 一个常量表达式;

  • new ValType() 形式的表达式,其中 ValType 是值类型,例如枚举或结构;

  • default(ValType) 形式的表达式,其中 ValType 是值类型。


typeof不一定返回编译时间常数,因为它可能会根据上下文返回不同的结果。

于 2012-01-20T09:49:57.663 回答
4

因为它不一定是一个常量表达式。您的示例在一个简单的类上具有 typeof,但是如果该类是通用的呢?显然,这不是一成不变的:

class MyClass<T>
{
  public void MyMethod(Type targetType = typeof(MyClass<T>))
  {
  }
} 
于 2012-01-20T09:55:32.490 回答
2

这是旧的,但如果有人正在寻找解决方法:

    class MyClass
    {
        public void MyMethod(Type targetType = null)
        {
            if(targetType == null)
            {
                targetType = typeof(MyClass);
            }
        }
    }

于 2019-06-14T19:21:54.963 回答
1

不是typeof(MyClass)编译时常量吗?

特定表达式是静态可解析的,是的,但typeof()在执行时评估(因为泛型),因此规则必须是typeof()调用不是编译时常量。

我确实想知道它是否C# 1.0 中,当时没有这样的论点......

于 2012-01-20T10:22:06.613 回答