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

How to create a Lazy property passing a string property of <this> class as parameter to it in C#?

有没有办法将名称 属性 作为参数传递给惰性 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)
    {
    }
}

不是在声明时实例化 Lazy<BOM>,而是在 Item 的构造函数中实例化它:

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; } }
}