为什么 DateTime const 的声明会给出编译器错误而不是可选参数?

Why does the declaration of a DateTime const give a compiler error but not optional parameter?

我觉得我不擅长标题。但请耐心等待:我知道为什么引用类型本身不能声明为 const - 它们必须在编译时完全可评估。因此,引用类型常量的唯一可能值是字符串和空引用。

所以 const DateTime x = some date 无效是有道理的。但是按照这个逻辑,我不应该能够传递例如 DateTime d1 = default(DateTime) 作为可选参数,就像我不能声明 const DateTime d1 = default(DateTime) 一样,因为可选参数必须是 compile-time 常量?这一直是我对 "meh. just the way it is" 的态度,但我现在很好奇。

compile-time 常数不是 compile-time 常数吗?如,常量就是常量?

当然,也可能是我的 IDE (Visual Studio) 只是给出了一个错误,因为 DateTime 不允许作为 const 并且它会编译得很好作为 default(DateTime)null 参考?

查看 optional parameters 上的 msdn 文章。 当数据类型是值类型(枚举、结构)时,您可以使用空构造函数启动可选参数:

static void Foo(string s, DateTime opt = new DateTime())

或使用默认关键字。这对引用类型不成立。