C#访问器和初始化

kno*_*ker 1 .net c#

我们如何组合c#访问器声明和初始化

List<string> listofcountries= new List<string>();
and 
List<string>listofcountries {get;set;}
Run Code Online (Sandbox Code Playgroud)

有没有办法将这些与声明结合起来?

Jon*_*eet 7

你现在不能.你将能够在C#6:

List<string> Countries { get; set; } = new List<string>();
Run Code Online (Sandbox Code Playgroud)

你甚至可以把它变成C#6中的只读属性(万岁!):

List<string> Countries { get; } = new List<string>();
Run Code Online (Sandbox Code Playgroud)

在C#5,你可以任意使用非自动实现的属性:

// Obviously you can make this read/write if you want
private readonly List<string> countries = new List<string>();
public List<string> Countries { get { return countries; } }
Run Code Online (Sandbox Code Playgroud)

...或者在构造函数中初始化它:

public List<string> Countries { get; set; }

public Foo()
{
    Countries = new List<string>();
}
Run Code Online (Sandbox Code Playgroud)

  • @eranotzap:嗯,不 - 仔细阅读.它说它不是*可用,包括C#5,但它计划在C#6中提供. (2认同)