简体   繁体   中英

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

Is there a way to pass the Name property as paramter to the 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)
    {
    }
}

You can use the factory overload of Lazy<T> to achieve this. This also means that the instantiation must, as Zohar's comment suggests, be moved to the constructor, as non static fields cannot be referenced from field initializers.

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)
    {
    }
}

Instead of instantiating the Lazy<BOM> at declaration, instantiate it in the constructor of 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; } }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM