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

前端 未结 1 1219
失恋的感觉
失恋的感觉 2021-02-12 18:46

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

public class Questionary
{
    private Lazy> _questions = n         


        
相关标签:
1条回答
  • 2021-02-12 19:12

    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; }
    }
    
    0 讨论(0)
提交回复
热议问题