问题描述
我想在实体中使用System.Lazy到Lazy初始化我的列表:
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; } }
}
问题出在我的SETTER上,出现此错误:属性' System.Lazy< T> .Value
'没有设置器
The problem is on my SETTER, get this error: The property 'System.Lazy<T>.Value
' has no setter
如果我想要做 MyInstance.Questions = new List< Question> {...}
?
我该如何进行?
更新:
我正试图避免这种情况:
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 } }
我做错了吗?
推荐答案
您可以执行以下操作:
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); }
}
}
但是,我不明白为什么需要 Lazy< T>
都在这里。使用它没有好处,因为新 List< T>
的初始化应该与新 Lazy< T>的初始化相同;
...
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; }
}
}
或
public class Questionary
{
public Questionary()
{
Questions = new List<Question>();
}
public IList<Question> Questions { get; set; }
}
这篇关于如何使用带有Setter的System.Lazy对POCO实体中的列表进行延迟初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!