c# - 为什么 C# 不允许将 typeof 作为默认参数?

标签 c# typeof default-parameters

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/

相关文章:

c# - 在 Windows Mobile 上使用 C# 和 C 或 C++ 的区别

c# - 在犀牛模拟中模拟 lambda

c# - 如何在wpf中的网格中添加列到行

javascript - 在 JavaScript 的 for-in 循环中使用 typeof

javascript - 在 JavaScript 中,typeof x == 'y' 和 typeof x === 'y' 之间有什么区别吗?

javascript - 'typeof' 运算符在这里说明了什么?

python - "Least Astonishment"和可变默认参数

c# - Windows 窗体没有扩展方法

scala - 使用参数默认值键入删除

c++ - 在其自身的默认值中使用参数名称 - 合法吗?