简体   繁体   English

为什么这个静态bool不需要初始化?

[英]Why does this static bool not need to be initialized?

if you call checkBool, it will always return "why does this not fail" 如果你调用checkBool,它将始终返回“为什么这不会失败”

Why is this and why do you not need to initialize _bool? 为什么这样,你为什么不需要初始化_bool?

public sealed class falsefalse
{
    private static bool _bool;
    public static string checkBool()
    {
        if (!_bool)
            return "why does this not fail";
        else return "";
    }
}

Fields of class have their default values if you don't initialize them explicitly. 如果您没有显式初始化它们,则类的字段具有其默认值 Default value for type bool is false . bool类型的默认值为false See C# specification 10.4.4 Field initialization : 参见C#规范10.4.4字段初始化

The initial value of a field, whether it be a static field or an instance field, is the default value (Section 5.2) of the field's type. 字段的初始值(无论是静态字段还是实例字段)是字段类型的默认值(第5.2节)。

Take a look at Default Values Table (C# Reference) 看一下默认值表(C#参考)

Fields are automatically initialized to their default. 字段会自动初始化为默认值。 default(bool) is false , so in this case - unless specified otherwise - _bool will be initialized to false . default(bool)false ,因此在这种情况下 - 除非另有说明 - 否则_bool将初始化为false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM