为什么我的本地变量可能会null,即使该方法返回了非null?

发布于 2025-02-04 12:43:07 字数 375 浏览 3 评论 0原文

我不确定这是Visual Studio还是C#...

如果expression.parameter()返回非零件parameterexpression(无问号),那么,为什么要将其返回值保存为潜在的null的局部变量? ie parameterexpression?而不是parameterexpression

我正在使用asp.net core 6.0.2和Visual Studio 2022 V17.1.3

I'm not sure if this is a bug in Visual Studio or C#...

If Expression.Parameter() returns a non-null ParameterExpression (no question mark), then why is a local variable that receives its return value being saved as potentially null? i.e. ParameterExpression? instead of ParameterExpression

enter image description here

I'm using ASP.NET Core 6.0.2 and Visual Studio 2022 v17.1.3

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等你爱我 2025-02-11 12:43:07

好吧,我不能告诉你为什么语言设计师以这种方式设计它,但是至少它是记录的行为( https://learn.microsoft.com/en-us/dotnet/csharp/csharp/language-reference-reference-reference-reference-reference-reference/keywords/keywords/var ):

当启用var与启用无效的参考类型一起使用时,即使表达式类型不能无效 ,它也总是意味着无效的参考类型。编译器的无效状态分析可保护取消潜在的无效价值。如果变量从未分配给可能无效的表达式,则编译器不会发出任何警告。如果将变量分配给可能为null的表达式,则必须测试它在避免任何警告之前就没有null。

它与据称是智能的答案所暗示的vs无关,这仅仅是如何针对启用无效的注释上下文指定var关键字。

Well, i can't tell you why the language designers designed it that way, but at least it's documented behavior (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var):

When var is used with nullable reference types enabled, it always implies a nullable reference type even if the expression type isn't nullable. The compiler's null state analysis protects against dereferencing a potential null value. If the variable is never assigned to an expression that maybe null, the compiler won't emit any warnings. If you assign the variable to an expression that might be null, you must test that it isn't null before dereferencing it to avoid any warnings.

It has nothing to do with VS supposedly being smart as the other answer alludes to, it simply is how the var keyword is specified with respect to nullable annotation context being enabled.

遗弃M 2025-02-11 12:43:07

可能是新的VS足够聪明,可以知道表达式。参数可能会返回一个空。

尽管它无法返回可确定的类型,但回来的值也可能为null。

我相信.NET 6他们对无效类型进行了一些更改 /更严格。

<PropertyGroup>
    <Nullable>enable</Nullable>
</PropertyGroup>

< -sharpcorner.com/article/how-to to handle-nullable-reference-in-net-6/

It might be that the new VS is smart enough to know that Expression.Parameter might return a null..

Even though it's not returning a nullable type, the VALUE that comes back could be null.

I believe in .NET 6 they have done some changes / being more strict on nullable types.

<PropertyGroup>
    <Nullable>enable</Nullable>
</PropertyGroup>

https://www.c-sharpcorner.com/article/how-to-handle-nullable-reference-in-net-6/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文