C#8中的不可为空的引用类型在运行时可以为null吗? [英] Can a non-nullable reference type in C# 8 be null in runtime?

查看:413
本文介绍了C#8中的不可为空的引用类型在运行时可以为null吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,真的不能保证非null变量永远不会为null.想象一下,我有一个具有不可为空的属性的类:

It seems to me there is really no guarantee that a non-nullable variable won't ever have null. Imagine I have a class that has one property that is not nullable:

public class Foo
{
    public Foo(string test)
    {
        Test = test;
    }
    public string Test {get;set;}
}

现在看来现在不能为null.但是,如果我们用另一个不使用可为空的上下文的库引用该类,则不会阻止它在其中发送null.

Now that might seem like it's now cannot be null. But if we reference this class with another library that does not use nullable context, nothing stops it from sending null in there.

是正确的还是有一些运行时检查,也许可以确保做到这一点?

Is that correct or there are some runtime checks as well perhaps that ensure this?

推荐答案

这是MS所说的( https://docs.microsoft.com/zh-cn/dotnet/csharp/tutorials/upgrade-to-nullable-references#interfaces -with-external-code ):

即使您的代码是在启用可空注释上下文的情况下编译的,编译器也无法验证对公共API的所有调用.此外,尚未选择使用可为空的引用类型的项目可能会占用您的库.验证公共API的输入,即使您已将其声明为非空类型.

The compiler can't validate all calls to your public APIs, even if your code is compiled with nullable annotation contexts enabled. Furthermore, your libraries may be consumed by projects that have not yet opted into using nullable reference types. Validate inputs to public APIs even though you've declared them as nonnullable types.

这篇关于C#8中的不可为空的引用类型在运行时可以为null吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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