中的未初始化变量

中的未初始化变量

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

问题描述

我有以下代码:

class Foo
{

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

        }
    }
}

class Bar { }

代码专家将已经看到这给出了错误. if 语句之前, Bar 可能未初始化.

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

bar的值是什么?它不应该为null吗?他们不是设置为null吗?(空指针?)

What is the value of bar? Shouldn't it be null? Aren't they set to null? (null pointer?)

推荐答案

否,局部变量没有默认值.阅读它们之前,必须先明确分配.这实际上减少了使用您赋予自己合理值的变量认为的机会,而实际上却具有一些默认值.对于实例变量或静态变量,无法完成此操作,因为您不知道将以什么顺序调用方法.

No, local variables don't have a default value. 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
{
}


就该语言而言,无论如何……显然,内存中的存储位置中有某物,但这是无关紧要的,并且与实现方式有关.通过创建带有 out 参数的方法,然后使用IL在方法中查看该参数的值的方法,您可以找到一种 值.,而没有赋予它其他价值.CLR完全不介意.然后,您可以调用,该方法传入一个不确定赋值的变量,lo并且看得出您可以检测到该值-基本上可能是全零"值.


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#中的未初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 10:06