有没有办法将Name属性作为参数传递给惰性BOM初始化?
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)
{
}
}
最佳答案
您可以使用Lazy<T>
的factory overload来实现。这也意味着,正如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)
{
}
}
关于c# - 如何创建在C#中将<this>类的字符串属性作为参数传递给它的Lazy属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49094189/