简体   繁体   English

C#奇怪的行为

[英]C# Strange Behavior

I have a custom struct : 我有一个自定义结构:

struct A
{
    public int y;
}

a custom class with empty constuctor: 具有空构造函数的自定义类:

class B
{
    public A a;
    public B()
    {
    }
}

and here is the main: 这是主要的:

static void Main(string[] args)
{
    B b = new B();
    b.a.y = 5;//No runtime errors!
    Console.WriteLine(b.a.y);
}


When I run the above program, it does not give me any errors, although I did not initialize struct A in class B constructor..'a=new A();' 当我运行上面的程序时,它没有给我任何错误,尽管我没有在B类构造函数中初始化struct A。.'a = new A();'

I did not initialize struct A in class B constructor. 我没有在B类构造函数中初始化structA。

C# does this for you. C#为您做到这一点。 All members of classes are initialized to their default values unless you assign them other values in their declaration or the constructor. 除非您在其声明或构造函数中为其分配其他值,否则所有类的成员都将初始化为其默认值。

For class instances, the default value is null and you'd get an error when using that instance. 对于class实例,默认值为null ,使用该实例时会出现错误。 However, for struct instances (which are not references unlike class instances), there doesn't exist a null value. 然而,对于struct实例(这是没有什么不同的类实例的引用),不存在一个null值。 The default value of a struct is an instance where all its fields have been default-initialized. 一个的默认值struct是这样的情况:所有的字段已经默认初始化。

That's why your code works. 这就是您的代码起作用的原因。

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

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