How to use System.Lazy with Setter to Lazy Initialization of List in POCO Entities?

冷暖自知 提交于 2020-02-26 11:31:15

问题


I want to use System.Lazy to Lazy Initialization of my List in my Entites:

public class Questionary
{
    private Lazy<List<Question>> _questions = new Lazy<List<Question>>(() => new List<Question>());

    public IList<Question> Questions { get { return _questions.Value; } set { _questions.Value = value; } }
}

The problem is on my SETTER, get this error: The property 'System.Lazy<T>.Value' has no setter

If i want to do MyInstance.Questions = new List<Question> { ... } ?

How do I proceed?

Update:

I'm trying to avoid that:

private IList<Question> _questions;

//Trying to avoid that ugly if in my getter:
public IList<Question> Questions { get { return _questions == null ? new List<Question>() : _questions; } set { _questions = value } }

I'm doing something wrong?


回答1:


You could do something like this:

public class Questionary
{
    private Lazy<IList<Question>> _questions = 
        new Lazy<IList<Question>>(() => new List<Question>());

    public IList<Question> Questions
    {
        get { return _questions.Value; }
        set { _questions = new Lazy<IList<Question>>(() => value); }
    }
}

However, I don't see why you need Lazy<T> here at all. There is no benefit in using it, because the initialization of a new List<T> should be the same as the initialization of a new Lazy<T>...

I think it would be enough to keep it as simple as this:

public class Questionary
{
    private IList<Question> _questions = new List<Question>();

    public IList<Question> Questions
    {
        get { return _questions; }
        set { _questions = value; }
    }
}

or

public class Questionary
{
    public Questionary()
    {
        Questions = new List<Question>();
    }

    public IList<Question> Questions { get; set; }
}



回答2:


It's not clear what you're trying to do. You can't set the value of a Lazy<T> - it's as simple as that. You can only ask it for a value, and it will execute the delegate you've provided the first time the values are requested.

Do you really need a setter in your class at all? Perhaps you just want:

public class Questionary
{
    private Lazy<List<Question>> _questions = 
        new Lazy<List<Question>>(() => new List<Question>());

    public IList<Question> Questions { get { return _questions.Value; } }
}



回答3:


Non-lazy solution - same benefit in terms of being initialized only when called:

    private List<Question> _questions;
    public List<Question> Questions { get { return _questions ?? (_questions = new List<Question>()); } set { _questions = value; } }


来源:https://stackoverflow.com/questions/6845261/how-to-use-system-lazy-with-setter-to-lazy-initialization-of-list-in-poco-entiti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!