ehh*_*ehh 1 c# lazy-initialization
有没有办法将Name属性作为参数传递给Lazy BOM Initialization?
public class Item
{
private Lazy<BOM> _BOM = new Lazy<BOM>(); // How to pass the Name as parameter ???
public Item(string name)
{
this.Name = name;
}
public string Name { get; private set; }
public BOM BOM { get { return _BOM.Value; } }
}
public class BOM
{
public BOM (string name)
{
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用工厂超负荷的Lazy<T>实现这一目标.这也意味着实例化必须像Zohar的注释所暗示的那样移动到构造函数,因为不能从字段初始化器引用非静态字段.
public class Item
{
private Lazy<BOM> _BOM;
public Item(string name)
{
this.Name = name;
_BOM = new Lazy<BOM>(() => new BOM(Name));
}
public string Name { get; private set; }
public BOM BOM { get { return _BOM.Value; } }
}
public class BOM
{
public BOM(string name)
{
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |