开发者

Pattern for forcing adding to collection through method in C#

开发者 https://www.devze.com 2023-01-09 09:13 出处:网络
I have a class with a collection member. I would like to prevent external code from modifying this collection directly, instead using methods (which can perform the appropriate validation etc).

I have a class with a collection member. I would like to prevent external code from modifying this collection directly, instead using methods (which can perform the appropriate validation etc).

This is harder than I tho开发者_如何学编程ught. Here is the solution I am using. Can you please tell me if there are better ways to do this common thing? It all just seems a little overengineered.

using System.Collections.Generic;
using System.Collections.ObjectModel;
public class Foo
  {
    private List<Bar> _bars = new List<Bar>();

    public ReadOnlyCollection<Bar> Bars { get { return _bars.AsReadOnly(); } } 

    public void AddBar(Bar bar) //black sheep
    {
      //Insert validation logic here
      _bars.Add(bar);
    }
  }


I think it's a good solution. This approach is discussed by Martin Fowler here Incapculate collection


There's nothing wrong with your approach, but you could alter your Bars-Property to be an IEnumerable if you want, since ReadOnlyCollection implements IEnumerable.

public class Foo
{
    private List<Bar> _bars = new List<Bar>();

    public IEnumerable<Bar> Bars { get { return _bars.AsReadOnly(); } }

    public void AddBar(Bar bar) //black sheep
    {
        //Insert validation logic here
        _bars.Add(bar);
    }
}

If you don't use .AsReadOnly() on your List, you could just cast IEnumeable back to List.

0

精彩评论

暂无评论...
验证码 换一张
取 消