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

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

问题描述

我已经发现了一些奇特的有关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.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从未分配,并且总是有它的默认值空

现在,如果VS是聪明的,知道的意志永远是空的,为什么是它不是一个错误以获得在第二个例子中其长度?我最初的猜测是,这仅仅给出一个编译错误如果编译器根本无法完成的工作。由于代码运行在技术上只要你不叫吧(),这只是一个警告。所不同的是说明由第一实施例失效。你仍然可以运行的代码没有错误,只要你不叫吧()。那么怎么办?只是一个疏忽,还是我失去了一些东西?

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?

推荐答案

第一个例子(误差)就是一个例子编译器的<一个HREF =http://msdn.microsoft.com/en-us/library/aa691172%28VS.71%29.aspx相对=nofollow>明确指派的跟踪,并且仅适用于本地变量。由于有限的情况下,编译器对这种情况的一个气密的抓地力。需要注意的是取值不为空,这是不确定的。

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.

在第二个例子中,小号是一个域(默认为空)。没有编译器错误,但它总是会在运行时被抓。这种特殊的情况下,可能会被困住,但这种错误不是一般检测由编译器。

为例,您可以添加一个方法条2()一个字符串>分配给<$ C $(C S),但后来把它比酒吧(),或根本没有。这将消除该警告而不是运行时错误。

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的空引用警告 - 为什么没有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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