我想在我的Entites中使用System.Lazy来懒惰初始化我的列表:
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
”没有设置器
如果我想MyInstance.Questions = new List<Question> { ... }
?
我该如何处理?
更新
我试图避免这种情况:
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 } }
我做错了什么?
答案 0 :(得分:25)
你可以这样做:
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>
的初始化相同......
我认为保持它如此简单就足够了:
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; }
}
答案 1 :(得分:5)
目前尚不清楚你要做什么。你无法设置Lazy<T>
的值 - 就这么简单。您只能询问它的值,它将执行您第一次请求值时提供的委托。
你真的需要班上的二传手吗?也许你只是想要:
public class Questionary
{
private Lazy<List<Question>> _questions =
new Lazy<List<Question>>(() => new List<Question>());
public IList<Question> Questions { get { return _questions.Value; } }
}
答案 2 :(得分:2)
非懒惰解决方案 - 仅在被调用时初始化时具有相同的好处:
private List<Question> _questions;
public List<Question> Questions { get { return _questions ?? (_questions = new List<Question>()); } set { _questions = value; } }