问题描述
本作品:
class MyClass
{
int a;
public MyClass()
{
int b = a;
}
}
但是,这给出了一个编译器错误(未分配使用局部变量'A'):
But this gives a compiler error ("Use of unassigned local variable 'a'"):
class MyClass
{
public MyClass()
{
int a;
int b = a;
}
}
据我可以告诉这是因为在第一个例子,在技术上,编译器不知道这是一个未分配。在后者的例子中,A是本地定义,因此容易跟踪。
As far as I can tell this happens because in the first example, technically, the compiler doesn't know that 'a' is not assigned. In the latter example, 'a' is defined locally, and therefore is easy to track.
但为什么后者的例子不工作?
But why does the latter example not work?
不要整数默认为0?这是不是编译器强制执行最佳做法。还是有另外一个原因?
Don't integers default to 0? Is this something the compiler enforces for "best practices". Or is there another reason?
推荐答案
在第一个例子是一个的字段的。字段自动默认为0 /假/空。在第二个例子中它是一个的可变的。变量的不的违约,必须在使用之前明确赋值。
In the first example it is a field. Fields automatically default to 0/false/null. In the second example it is a variable. Variables are not defaulted, and must have "definite assignment" before they are used.
从本质上讲,创建一个对象(或初始化一个结构时, ),它的归零内存(或在非默认的构造函数结构的情况下,迫使你手动初始化一切)。然而,变量是如此普遍(在每一个方法),它不希望具有零堆栈的所有时间的开销。相反,它迫使你以指示初始值。
Essentially, when creating an object (or initializing a struct) it zeros the memory (or in the case of a non-default struct ctor, forces you to manually initialize everything). However, variables are so common (in every method) that it doesn't want the overhead of having to zero the stack all the time. It instead forces you to indicate the initial value.
这篇关于我为什么要值在C#中的默认值时,分配给一个int为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!