问题描述
我有以下代码:
class Foo
{
public Foo()
{
Bar bar;
if (null == bar)
{
}
}
}
class Bar { }
代码专家已经看到这会产生错误.Bar 可能不会在 if 语句之前初始化.
Code gurus will already see that this gives an error. Bar might not be initialized before the if statement.
什么是 bar 的值?它不应该为空吗?他们不是设置为null吗?(空指针?)
What is the value of bar? Shouldn't it be null? Aren't they set to null? (null pointer?)
推荐答案
不,局部变量没有默认值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.
请注意,这与 this 作为引用类型变量无关.这将无法以相同的方式编译:
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 就语言而言,无论如何...显然内存中的存储位置有 something 在其中,但它无关紧要且特定于实现.one 方法可以让您找出该值是什么,方法是创建一个带有 out
参数的方法,然后使用 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#中的非初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!