class MyClass
{
public void MyMethod(Type targetType = typeof(MyClass))
{
}
}
是不是typeof(MyClass)
編譯時常量?爲什麼C#不允許typeof作爲默認參數?
class MyClass
{
public void MyMethod(Type targetType = typeof(MyClass))
{
}
}
是不是typeof(MyClass)
編譯時常量?爲什麼C#不允許typeof作爲默認參數?
從MSDN - Named and Optional Parameters:
A default value must be one of the following types of expressions:
a constant expression;
an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
an expression of the form default(ValType), where ValType is a value type.
typeof
不一定返回編譯時間常數,因爲它可以根據上下文返回不同的結果。
因爲它不一定是一個常量表達式。你的例子在一個簡單的類上有一個typeof,但是如果這個類是通用的呢?顯然這是不恆定迄今爲止:
class MyClass<T>
{
public void MyMethod(Type targetType = typeof(MyClass<T>))
{
}
}
我不是IL專家,但似乎它來電L_0005的方法:
return typeof(int);
It's相同的:
.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
Isn't
typeof(MyClass)
a compile-time constant?
即特定表達是靜態解析的,是的,但typeof()
在執行時(因爲泛型)被評估,所以規則必須是一個typeof()
調用不是編譯時常量。
我不知道它是否在C#1.0中,當有來作出上述說法 ...
我不認爲泛型是唯一的原因。我認爲這是因爲它的工作原理:'typeof(ClassInExternalAssembly)'。在實際的外部裝配被加載之前它不能被解決,因此它不是恆定的。 – Aidiakapi
類型傳遞給'typeof'必須在編譯時得到解決。因此我看不出你的意思。如果你說的是真的,屬性也應該禁止'類型常量'。 – leppie
leppie,你的意思是「屬性也應該禁止'類型常量'」?屬性在什麼地方將值限制爲常量? –
@Fujiy - 傳遞給屬性構造函數的參數需要是編譯時間常量。 – Oded