且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我为什么要值在C#中的默认值时,分配给一个int为0?

更新时间:2023-11-13 08:40:28

在第一个例子是一个的字段的。字段自动默认为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.