class MyClass
{
public void MyMethod(Type targetType = typeof(MyClass))
{
}
}
不是typeof(MyClass)
编译时常量吗?
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
来自 MSDN -命名和可选参数:
默认值必须是以下表达式类型之一:
一个常量表达式;
new ValType() 形式的表达式,其中 ValType 是值类型,例如枚举或结构;
default(ValType) 形式的表达式,其中 ValType 是值类型。
typeof
不一定返回编译时间常数,因为它可能会根据上下文返回不同的结果。
因为它不一定是一个常量表达式。您的示例在一个简单的类上具有 typeof,但是如果该类是通用的呢?显然,这不是一成不变的:
class MyClass<T>
{
public void MyMethod(Type targetType = typeof(MyClass<T>))
{
}
}
这是旧的,但如果有人正在寻找解决方法:
class MyClass
{
public void MyMethod(Type targetType = null)
{
if(targetType == null)
{
targetType = typeof(MyClass);
}
}
}
不是
typeof(MyClass)
编译时常量吗?
该特定表达式是静态可解析的,是的,但typeof()
在执行时评估(因为泛型),因此规则必须是typeof()
调用不是编译时常量。
我确实想知道它是否在C# 1.0 中,当时没有这样的论点......