如何在C#中创建一个将<this>类的字符串属性作为参数传递给它的Lazy属性?

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)

Col*_*inM 5

您可以使用工厂超负荷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)

  • 该死的!太快半分钟!:-) (2认同)
  • @ZoharPeled我喝了太多咖啡 (2认同)
  • 我还没吃够:-) (2认同)