属性 初始值设定项 vs 旧的初始化方式 属性 。你能澄清一下吗
Property initializers vs old way of initializing property .Can you clarify
用谷歌搜索但找不到 属性 初始值设定项
用法的解释
有人能告诉我下面的代码是否相同吗?使用 属性 初始化器的属性是否只实例化一次?
这三种初始化列表的方式在效率和最佳实践方面有什么区别
1) private List<Address>Addresses
{
get
{
return addresses ?? (addresses = new List<Address>());
}
}
2) public List<Address> Addresses{ get; set; } = new List<Address>();
3) within constructor Addresses= new List<Address>()
感谢您的澄清!
示例 2 和 3 在创建每个实例后立即初始化 属性。
示例 1 初始化 属性 lazily;它通过仅在第一次调用 属性 getter 时初始化支持字段来实现这一点(当支持字段仍未初始化时)。如果实例的 Addresses
属性 从未被访问过,则支持字段在给定实例的整个生命周期内完全有可能保持未初始化状态。
惰性初始化是否更有效完全取决于 属性 及其使用方式。
示例 2 的 pre-C#6 等效于 不是 惰性初始化,而是以下内容:
public List<Address> Addresses { get; set; }
... 在构造函数中完成初始化。在同一语句中声明和初始化 auto-implemented 属性 是 C# 6 的新增功能。
首先,不要对属性使用class的具体实现,使用接口(例如IList)。其次,我更喜欢在默认构造函数中将 属性 初始化为您的地址,然后从另一个构造函数调用此构造函数。
例如:
public class MyClass1
{
public IList<MyPropertyClass1> Property1{get; protected set;}
public MyPropertyClass2 Property2{get; protected set;}
...
public MyClass1()
{
//I initialize Property1 by empty List<T>=> internal logic will not crashed if user try to set Property1 as null.
Property1=new List<MyPropertyClass1>();
Property2=default(MyPropertyClass2);
...
}
public MyClass1(IList<MyPropertyClass1> property1, MyPropertyClass2 property2)
:this()
{
if(property1!=null)
{
Property1=property1;
}
if(property2!=default(MyPropertyClass2))
{
Property2=property2;
}
}
}
用谷歌搜索但找不到 属性 初始值设定项
用法的解释有人能告诉我下面的代码是否相同吗?使用 属性 初始化器的属性是否只实例化一次?
这三种初始化列表的方式在效率和最佳实践方面有什么区别
1) private List<Address>Addresses
{
get
{
return addresses ?? (addresses = new List<Address>());
}
}
2) public List<Address> Addresses{ get; set; } = new List<Address>();
3) within constructor Addresses= new List<Address>()
感谢您的澄清!
示例 2 和 3 在创建每个实例后立即初始化 属性。
示例 1 初始化 属性 lazily;它通过仅在第一次调用 属性 getter 时初始化支持字段来实现这一点(当支持字段仍未初始化时)。如果实例的 Addresses
属性 从未被访问过,则支持字段在给定实例的整个生命周期内完全有可能保持未初始化状态。
惰性初始化是否更有效完全取决于 属性 及其使用方式。
示例 2 的 pre-C#6 等效于 不是 惰性初始化,而是以下内容:
public List<Address> Addresses { get; set; }
... 在构造函数中完成初始化。在同一语句中声明和初始化 auto-implemented 属性 是 C# 6 的新增功能。
首先,不要对属性使用class的具体实现,使用接口(例如IList)。其次,我更喜欢在默认构造函数中将 属性 初始化为您的地址,然后从另一个构造函数调用此构造函数。 例如:
public class MyClass1
{
public IList<MyPropertyClass1> Property1{get; protected set;}
public MyPropertyClass2 Property2{get; protected set;}
...
public MyClass1()
{
//I initialize Property1 by empty List<T>=> internal logic will not crashed if user try to set Property1 as null.
Property1=new List<MyPropertyClass1>();
Property2=default(MyPropertyClass2);
...
}
public MyClass1(IList<MyPropertyClass1> property1, MyPropertyClass2 property2)
:this()
{
if(property1!=null)
{
Property1=property1;
}
if(property2!=default(MyPropertyClass2))
{
Property2=property2;
}
}
}