我们如何组合c#访问器声明和初始化
List<string> listofcountries= new List<string>();
and
List<string>listofcountries {get;set;}
Run Code Online (Sandbox Code Playgroud)
有没有办法将这些与声明结合起来?
你现在不能.你将能够在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)