非在C#中初始化变量 [英] Non initialized variable in C#

查看:162
本文介绍了非在C#中初始化变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面这段code:

I have the following piece of code:

class Foo
{

    public Foo()
    {
        Bar bar;
        if (null == bar)
        {

        }
    }
}

class Bar { }

code大师们都已经看到,这给出了一个错误。酒吧可能不会if语句之前必须初始化。

Code gurus will already see that this gives an error. Bar might not be initialized before the if statement.

所以,现在我想知道:什么是酒吧的vlaue,应该不是为空?他们不是设置为空? (空指针?)

So now I'm wondering: what IS the vlaue of bar, shouldn't it be null? Aren't they set to null? (nullpointer?)

推荐答案

没有,局部变量没有默认值 1 。他们必须的明确赋值的阅读它们。使用你的觉得一个变量这样可以减少你的机会的你给一个合理的值,而实际上它有一些默认值。这不能做了实例或静态变量,因为你不知道以什么顺序的方法将被调用。

No, local variables don't have a default value1. They have to be definitely assigned before you read them. This reduces the chance of you using a variable you think you've given a sensible value to, when actually it's got some default value. This can't be done for instance or static variables because you don't know in what order methods will be called.

见的C#3.0规范的5.3明确赋值的更多细节。

See section 5.3 of the C# 3.0 spec for more details of definite assignment.

请注意,这已经无关,与这是一个引用类型变量。这将失败以同样的方式来编译:

Note that this has nothing to do with this being a reference type variable. This will fail to compile in the same way:

int i;
if (i == 0) // Nope, i isn't definitely assigned
{
}


1 就语言而言,反正...显然在内存中的存储位置具有的的东西的它,但它是不相关的,具体实现的。还有的一个的方式,你可以找出该值,通过创建一个退出参数的方法,但随后用IL看价值该方法中的参数,而不必给它另一个值。在CLR不介意的。然后,您可以的通话的这种方法传递一个不明确分配的变量,你瞧,你可以检测值 - 这很可能是全零值基本上


1 As far as the language is concerned, anyway... clearly the storage location in memory has something in it, but it's irrelevant and implementation-specific. There is one way you can find out what that value is, by creating a method with an out parameter but then using IL to look at the value of that parameter within the method, without having given it another value. The CLR doesn't mind that at all. You can then call that method passing in a not-definitely-assigned variable, and lo and behold you can detect the value - which is likely to be the "all zeroes" value basically.

我怀疑是CLI规范的确实的实施有一个默认值的局部变量 - 但我不得不检查。除非你正在做的恶事像上面的,它不应该向你的C#。

I suspect that the CLI specification does enforce local variables having a default value - but I'd have to check. Unless you're doing evil things like the above, it shouldn't matter to you in C#.

这篇关于非在C#中初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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