问题描述
为什么必须在方法内部初始化变量?
Why must I initialize variables inside methods?
int test1; // Not initialized, but OK
public int Foo()
{
int test2; // Not initialized
int test3 = test1; // OK
int test4 = test2; // An error
}
推荐答案
字段会自动初始化为该类型的逻辑零;这是隐式的.变量必须服从确定分配",因此必须先分配 才能读取它们.
Fields are automatically initialized to the logical zero for the type; this is implicit. Variables must obey "definite assignment", so must be assigned before they can be read.
ECMA 334v4
ECMA 334v4
字段的初始值,是否它可以是静态字段或实例字段,是默认值(§12.2)字段的类型.这不可能观察一个字段的值之前这个默认的初始化有发生,因此永远不会有一个领域未初始化".
The initial value of a field, whether it be a static field or an instance field, is the default value (§12.2) of the field’s type. It is not possible to observe the value of a field before this default initialization has occurred, and a field is thus never "uninitialized".
和
...必须在变量之前明确分配一个变量(第12.3节)可以获得价值....
... A variable shall be definitely assigned (§12.3) before its value can be obtained. ...
这篇关于为什么局部变量必须具有初始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!