简体   繁体   English

c#数据类成员在声明时实例化

[英]c# data class members are instantiated at declaration

I am working on a project where a lot of the data classes look like this: 我正在一个项目中,其中许多数据类如下所示:

[DataMember]
public List<SpecialOpeningHours> SpecialOpeningHours { get; set; } = new List<SpecialOpeningHours>();

I've never seen this before and would normally just do this: 我以前从未见过,通常只会这样做:

[DataMember]
public List<SpecialOpeningHours> SpecialOpeningHours { get; set; }

Can anyone explain why the list in instantiated in this way and whether or not there is some advantage? 谁能解释为什么以这种方式实例化列表以及是否有一些优势? It doesn't seem to make any difference in use. 它的使用似乎没有什么区别。 I am using Dapper and get the same result populating the list either way. 我正在使用Dapper并以相同的方式填充列表获得相同的结果。

Your first example is just a shortcut introduced on C#6 for this: 您的第一个示例只是为此在C#6上引入的快捷方式:

public MyClass()
{
    this.SpecialOpeningHours = new List<SpecialOpeningHours>();
}

Now compare this with: 现在将其与:

public MyClass()
{
    this.SpecialOpeningHours = null;
}

The former is what your first option is translated into when compiling, the second one is what you get when you don´t add any initial value. 前者是编译时第一个选项的翻译结果,第二个是不添加任何初始值时得到的结果。 In particular your second example will cause a NullReferenceException as soon as you call any of its members, whereby the first one will run fine. 特别是,您的第二个示例将在您调用任何一个成员后立即引发NullReferenceException,因此第一个示例将正常运行。

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

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