将通用集合公开为只读是否有良好的模式?

Joe*_*tti 6 c# architecture generics wpf design-patterns

所以我有这些类暴露了一组子对象.

我不希望其他类添加或删除集合中的对象,因为我需要连接到子对象中的事件,因此当它们被添加或删除时,我希望能够进行其他处理.但我真的很喜欢内部操纵泛型的简易性.

我提到这是一个WPF应用程序,所以我需要INotifySupport吗?

我能想到的最好的就是这样的.

public class foo : INotifyPropertyChanged
{
    protected List<ChildFoo> _Children = new List<ChildFoo>();

    public foo()
    {
    }

    public void AddChild(ChildFoo newChild)
    {
        DoAttachLogic(newChild);
        _Children.Add(newChild);
        NotifyPropertyChange("Children");
    }

    public void RemoveChild(ChildFoo oldChild)
    {
        DoRemoveLogic(oldChild);
        _Children.Remove(oldChild);
        NotifyPropertyChange("Children");
    }

    public ChildFoo[] Children
    {
        get
        {
            return _Children.ToArray();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

我没有看到这种设计存在严重缺陷吗?

每次访问Children属性时,我们都会将列表转换为数组.

对此的任何建议都会很棒.

Jon*_*len 5

这就是我为普通代码所做的事情:

Public Readonly Property Childern As ObjectModel.ReadOnlyCollection(Of Child)
    Get
       Return New ObjectModel.ReadOnlyCollection(Of Child)(_ChildernList)
    End Get
End Property
Run Code Online (Sandbox Code Playgroud)

对于WPF代码,我只是公开一个ObservableCollection的子类.


Eup*_*ric 0

您应该使用 ObservableCollection 作为类中的字段,然后您就可以完全访问修改集合。然后通过属性将其公开为ReadonlyObservableCollection。如果您不更改集合本身(例如, no children = new ObservableCollection()​​,您应该将字段设置为只读),那么您不需要对此属性进行任何类型的notifyPropertyChanged,因为它不会更改,并且集合本身会为其子级处理这些事件。

public class Child
{
    public int Value { get; set; }
}

class MyClassWithReadonlyCollection
{
    private readonly ObservableCollection<Child> _children = new ObservableCollection<Child>();

    public MyClassWithReadonlyCollection()
    {
        _children.Add(new Child());
    }

    //No need to NotifyPropertyChange, because property doesnt change and collection handles this internaly
    public ReadOnlyObservableCollection<Child> Children { get { return new ReadOnlyObservableCollection<Child>(_children); } }
}
Run Code Online (Sandbox Code Playgroud)