为什么我必须在默认为 0 时为 C# 中的 int 赋值? [英] Why do I have to assign a value to an int in C# when defaults to 0?

查看:59
本文介绍了为什么我必须在默认为 0 时为 C# 中的 int 赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这行得通:

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 赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆