小编Bar*_*ing的帖子

如何返回一个空的ReadOnlyCollection

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

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

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

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

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

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

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

c# collections properties readonly

7
推荐指数
2
解决办法
4285
查看次数

标签 统计

c# ×1

collections ×1

properties ×1

readonly ×1