初始化集合,以便用户不必

And*_*ite 4 c# collections

这可能是一个愚蠢的问题,但是有没有为用户初始化集合属性的常见做法,所以在类中使用之前,他们不必新建一个新的具体集合?

这些中的任何一个都优先于另一个吗?

选项1:

public class StringHolderNotInitialized
{
    // Force user to assign an object to MyStrings before using
    public IList<string> MyStrings { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

选项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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

选项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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

选项4:

还有其他好的选择吗?

cas*_*One 10

在这种情况下,我没有看到延迟加载的原因,所以我会选择2.如果你创建了大量的这些对象,那么产生的分配和GC的数量将是一个问题,但那是除非事后证明是一个问题,否则不要考虑.

另外,对于这样的事情,我通常不允许将IList赋值给类.我会把这个只读.在不控制IList的实现的情况下,您可以打开自己的意外实现.