这可能是一个愚蠢的问题,但是是否有任何常见的做法可以为用户初始化集合属性,这样他们就不必在类中使用之前新建一个新的具体集合?
这些中的任何一个比另一个更受欢迎吗?
选项 1:
public class StringHolderNotInitialized
{
// Force user to assign an object to MyStrings before using
public IList<string> MyStrings { get; set; }
}
选项 2:
public class StringHolderInitializedRightAway
{
// Initialize a default concrete object at construction
private IList<string> myStrings = new List<string>();
public IList<string> MyStrings
{
get { return myStrings; }
set { myStrings = value; }
}
}
选项 3:
public class StringHolderLazyInitialized
{
private IList<string> myStrings = null;
public IList<string> MyStrings
{
// If user hasn't set a collection, create one now
// (forces a null check each time, but doesn't create object if it's never used)
get
{
if (myStrings == null)
{
myStrings = new List<string>();
}
return myStrings;
}
set
{
myStrings = value;
}
}
}
选项 4:
还有其他好的选择吗?
最佳答案
在这种情况下,我看不出延迟加载的原因,所以我会选择选项 2。如果您要创建大量这样的对象,那么分配和 GC 的数量将是一个问题,但这不是真正需要考虑的事情,除非它后来被证明是一个问题。
此外,对于这样的事情,我通常不允许将 IList 分配给类。我会将其设为只读。如果不控制 IList 的实现,您就会面临意外的实现。
关于c# - 初始化一个集合,这样用户就不必,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/559858/