问题描述
这行得通:
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".在后一个示例中,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/false/null.在第二个示例中,它是一个变量.变量不是默认的,在使用之前必须有明确的赋值".
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.
本质上,在创建对象(或初始化结构)时,它会将内存归零(或者在非默认结构 ctor 的情况下,强制您手动初始化所有内容).但是,变量非常常见(在每种方法中),它不希望始终将堆栈归零的开销.相反,它会强制您指明初始值.
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.
这篇关于为什么我必须在默认为 0 时为 C# 中的 int 赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)