Visual Studio null引用警告 - 为什么没有错误? [英] Visual Studio null reference warning - why no error?

查看:912
本文介绍了Visual Studio null引用警告 - 为什么没有错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到了关于Visual Studio的一些奇怪的东西。首先,尝试在函数中的某个地方键入(C#):

I've noticed something peculiar about Visual Studio. First, try typing this (C#) somewhere in a function:

class Foo  
{  
    public void Bar()  
    {  
        string s;
        int i = s.Length;
    }
}

现在,马上就会标记 s 在 s.Length 中作为错误,说使用未分配的局部变量' code>。另一方面,尝试下面的代码:

Now, right away it will mark the s in s.Length as an error, saying "Use of unassigned local variable 's'". On the other hand, try this code:

class Foo  
{  
    private string s;
    public void Bar()  
    {  
        int i = s.Length;
    }
}

它将编译并加上<$ c $在中的 s ,带有警告,说字段'Foo.s'

It will compile, and underline the s in private string s with a warning, saying "Field 'Foo.s' is never assigned to, and will always have its default value null".

现在,如果VS是聪明的,并且知道s将永远为null,为什么是它不是一个错误,得到它的长度在第二个例子?我的原始猜测是,它只给出一个编译错误,如果编译器根本不能完成它的工作。由于代码技术上运行只要你从来没有调用Bar(),它只是一个警告。除了第一个例子的说明无效。你仍然可以运行代码,没有错误,只要你从不调用Bar()。那么什么给了?

Now, if VS is that smart and knows that s will always be null, why is it not an error to get its length in the second example? My original guess was, "It only gives a compile error if the compiler simply cannot complete its job. Since the code technically runs as long as you never call Bar(), it's only a warning." Except that explanation is invalidated by the first example. You could still run the code without error as long as you never call Bar(). So what gives? Just an oversight, or am I missing something?

推荐答案

第一个示例(错误)是编译器的定义分配跟踪,仅适用于局部变量。由于有限的上下文,编译器对这种情况有一个气密的把握。请注意, s 不为null,未定义。

The first example (the error) is an example of the Compiler's definite-assignment tracking and that is only applied to local variables. Due to the limited context, the compiler has an airtight grip on this situation. Note that s is not null, it is undefined.

在第二个示例中, s 是一个字段(默认为null)。没有编译器错误,但它将始终在运行时捕获。这种特殊情况可能被捕获,但这种错误通常不能被编译器检测到。

例如,您可以添加一个方法 Bar2() s 分配一个字符串,但稍后调用 Bar(),或者根本不调用。这将消除警告,而不是运行时错误。

In the second example, s is a field (and defaults to null). There is no compiler error, but it will always be caught at runtime. This particular case could be trapped but this kind of error is not in general detectable by the compiler.
For example, you could add a method Bar2() that assigns a string to s but call it later than Bar(), or not at all. That would eliminate the warning but not the runtime error.

这是设计。

这篇关于Visual Studio null引用警告 - 为什么没有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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