简体   繁体   English

C# 8 的可空引用类型

[英]Nullable Reference Types with C# 8

Null reference exceptions are one of the top sources of program failures. Null 引用异常是程序失败的主要来源之一。 Tony Hoare called it his billion dollar mistake.托尼·霍尔称之为他的十亿美元错误。 So I'm particularly looking forward to C# 8 and the new nullable reference types feature.所以我特别期待 C# 8 和新的可空引用类型功能。 I think I've got a pretty good grasp of the feature and what it's going to mean for my code.我想我已经很好地掌握了这个特性以及它对我的代码意味着什么。 There is one aspect I'm struggling the get my head around though and that's how default will behave.不过,有一个方面我正在努力解决问题,这就是default的行为方式。

Currently in C# default(string) will return null.目前在 C# default(string)将返回 null。 But when C# 8 comes along then doing something like string x = default(string);但是当 C# 8 出现时,就会执行类似string x = default(string);的操作。 should surely give a compiler warning straight off the bat.肯定应该立即给出编译器警告。 Seems like this is a bit of a paradox.这似乎有点悖论。 I'm also wondering if default(string?) will be possible and what would it even return.我还想知道default(string?)是否可能,它甚至会返回什么。 I guess it would have to be null which just adds to my confusion.我想它必须是 null 这只会增加我的困惑。

I don't think there has been a preview release of this feature yet, but I was wondering if anyone knows yet how this will be handled.我认为这个功能还没有预览版,但我想知道是否有人知道如何处理这个问题。

This question is possible to answer now, rather than waiting for C# 8 to be released. 现在可以回答这个问题,而不用等待C#8的发布。 C# is now developed "in the open", so just ake yourself over to SharpLab , select the NullabaleReferenceTypes branch and try the code. C#现在是“公开”开发的,因此让自己进入SharpLab ,选择NullabaleReferenceTypes分支并尝试代码。

It gives a warning CS8600: Cannot convert null to non-nullable reference. 它发出warning CS8600: Cannot convert null to non-nullable reference. as default of a reference type is null and null should not be assigned to the non-nullable string . default ,引用类型为null并且不应将null分配给不可为null的string

If you'd prefer to test a preview in VS2017, a preview plugin is available for the IDE, too . 如果您希望在VS2017中测试预览, 则IDE还可使用预览插件

I was curious, too.我也很好奇。

default(string?) // no warning, returns null when nullable reference types are enabled
default(string) // warning CS8603 when nullable reference types are enabled, but it compiles successfully and actually, it returns null, too.

That means: In the following scenario, string a is not nullable, but it is actually null.这意味着:在以下场景中,字符串a不可为空,但实际上是 null。

string MyMethod(){
    return default;
}
string a = MyMethod();

So, if MyMethod comes from a foreign library with NullableReferenceTypes enabled, it's still possible that the library developers messed something up and that the method returns null.因此,如果MyMethod来自启用了 NullableReferenceTypes 的外部库,则库开发人员仍然可能搞砸了,并且该方法返回 null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM