class MyClass
{
public void MyMethod(Type targetType = typeof(MyClass))
{
}
}
typeof(MyClass)
不是编译时常量吗?
最佳答案
我不是 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
关于c# - 为什么 C# 不允许将 typeof 作为默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8939433/