5

我有一个名为Person包含属性、父级和子级列表的类。

我希望每个人都只使用AddChildMethod 来添加孩子,而不是List.Addmethod ,那么我该如何限制使用呢?

public class Person
{
  private List<Person> _children = new List<Person>();
  public string Name { get; set; }
  public Person Father { get; set; }
  public List<Person> Children 
  { 
    get
    {
       return _children;
    } 
  }
  public void AddChild(string name)
  {
      _children.Add( new Person { Name = name, Father = this });
  }
}
4

7 回答 7

12

将孩子公开为 ReadOnlyCollection:

public IList<Person> Children  
{  
    get 
    { 
       return new ReadOnlyCollection<Person>(_children);
    }  
} 
于 2009-10-07T11:46:19.523 回答
8

暴露ChildrenIEnumerable<T>

于 2009-10-07T11:46:48.273 回答
8

将您的 Children 属性更改为:

public IList<Person> Children 
{ 
  get
  {
     return _children.AsReadOnly();
  } 
}
于 2009-10-07T11:49:18.660 回答
7

如果您要暴露底层证券List<T>,那么简而言之:您不能。

您可以编写自己的集合包装类,或者继承自Collection<T>(它仍然公开Add,但您可以override在添加数据之前进行一些事情来检测数据)。

于 2009-10-07T11:47:47.900 回答
3

将 Children 属性公开为ReadOnlyCollection<Person>

public ReadOnlyCollection<Person> Children
{
     get {return _children.AsReadOnly();}
}
于 2009-10-07T11:49:06.383 回答
3

如果您使用的是 .NET 4.5 或更高版本,则可以返回_childrenIReadOnlyList<T>

public IReadOnlyList<Person> Children
{
    get
    {
        return _children;
    }
}

这与返回IList<Person>via有何不同_children.AsReadOnly()IReadOnlyList<Person>甚至没有变异方法。考虑以下代码:

somePerson.Children[0] = null;

使用IReadOnlyList<Person>此代码时将无法编译。使用.AsReadOnly()此代码时会导致运行时异常。

这与返回ReadOnlyCollection<Person>via有何不同_children.AsReadOnly()?没有ReadOnlyCollection<Person>创建包装对象。除此之外,我没有看到很大的不同。

于 2013-11-27T07:22:07.403 回答
2

一个 IEnumerable 工作得很好:

public IEnumerable<Person> Children
{
    get
    {
        return _children.AsReadOnly();
    }
}

或更冗长的:

public IEnumerable<Person> Children
{
    get
    {
        foreach (Person child in _children)
        {
            yield return child;
        }
    }
}
于 2009-10-07T11:53:40.447 回答