在可为空的可选参数中使用 C# 7.1 默认文字会导致意外行为 [英] Using C# 7.1 default literal in nullable optional argument causes unexpected behavior

查看:59
本文介绍了在可为空的可选参数中使用 C# 7.1 默认文字会导致意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 7.1 引入了一项名为默认文字"的新功能,该功能允许使用新的 default 表达式.

C# 7.1 introduces a new feature called "Default Literals" that allows new default expressions.

// instead of writing
Foo x = default(Foo);

// we can just write
Foo x = default;

对于 Nullable<T> 类型,默认值为 null,按照通常的用法,它按预期工作:

For Nullable<T> types, the default value is null, and with the usual usage this works as expected:

int? x = default(int?); // x is null

int? x = default; // x is null

但是,当我尝试使用新的默认文字作为函数的可选参数(参数)时,它没有按预期工作:

However, when I try to use the new default literal as an optional argument (parameter) of a function, it's not working as expected:

static void Foo(int? x = default(int?))
{
    // x is null
}

static void Foo(int? x = default)
{
    // x is 0 !!!
}

对我来说,这种行为是出乎意料的,看起来像是编译器中的一个错误.

To me, this behavior is unexpected and looks like a bug in the compiler.

任何人都可以确认错误,或解释这种行为吗?

推荐答案

经过网上的更多研究,我发现这是一个已确认的错误:

After more research online, I found out that it's a known confirmed bug:

它已经修复并将成为 C# 7.2 的一部分.

这篇关于在可为空的可选参数中使用 C# 7.1 默认文字会导致意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆