在可空可选参数中使用C#7.1默认字面值导致意外行为
问题描述:
C#7.1引入了一个名为“Default Literals”的新功能,该功能允许使用新的default
表达式。在可空可选参数中使用C#7.1默认字面值导致意外行为
// instead of writing
Foo x = default(Foo);
// we can just write
Foo x = default;
对于Nullable<T>
类型,默认值是null
,并与通常使用这种按预期工作:
int? x = default(int?); // x is null
int? x = default; // x is null
然而,当我尝试使用新的默认文字作为可选参数(函数的参数),它不是按预期工作:
static void Foo(int? x = default(int?))
{
// x is null
}
static void Foo(int? x = default)
{
// x is 0 !!!
}
对我来说,这种行为是意外的,看上去就像在组合物1中的错误LER。
任何人都可以确认错误,或解释此行为?
答
更多的研究后在网上,我发现,这是已知的确认的错误: