如何返回一个空的ReadOnlyCollection

时间:2013-09-17 14:07:25

标签: c# collections properties readonly

在我的域对象中,我将1:M关系映射到IList属性。

为了获得良好的隔离,我以这种方式将其设为只读:

private IList<PName> _property;
public ReadOnlyCollection<PName> Property
{
    get
    {
        if (_property!= null)
        {
            return new ReadOnlyCollection<PName>(new List<PName>(this._property));
        }
    }
}

我不太喜欢ReadOnlyCollection,但没有找到使集合成为只读的接口解决方案。

现在我想编辑属性声明以使其返回空列表而不是null当它为空时,所以我用这种方式编辑它:

if (_property!= null)
{
    return new ReadOnlyCollection<PName>(new List<PName>(this._property));
}
else
{
    return new ReadOnlyCollection<PName>(new List<PName>());
}

但是当我在测试中得到它时,Property总是为空。

4 个答案:

答案 0 :(得分:7)

由于它只读和空,将其存储在静态中是安全的:

private static readonly ReadOnlyCollection<PName> EmptyPNames = new List<PName>().AsReadOnly();

然后在任何需要的地方重复使用它,例如:

if (_property!= null)
{
    return new ReadOnlyCollection<PName>(new List<PName>(this._property));
}    
else
{
    return EmptyPNames;
}

答案 1 :(得分:1)

也许您可以使用IEnumerable而不是ReadOnlyCollection:

private IList<PName> _property = new List<PName>();
public IEnumerable<PName> Property
{
    get
    {
        return _property;
    }
}

答案 2 :(得分:1)

如果您为IList设置默认值

,该怎么办?
private IList<PName> _property = new IList<PName>();
public ReadOnlyCollection<PName> Property
{
    get
    {
        return _property
    }
}

答案 3 :(得分:0)

其他可能的解决方案是以这种方式编辑类构造函数:

public MyObject (IList<PName> property)
{
  this._property = property ?? new List<PName>();
}