禁止对列表< T>进行公共添加和删除. [英] Forbid public Add and Delete for a List<T>

查看:44
本文介绍了禁止对列表< T>进行公共添加和删除.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C#项目中,我有一个包含列表的类

 公共类MyClass{MyClass公共父级;公共列表< MyClass>孩子们;...} 

我想防止类的用户向子列表添加(和删除)元素,但是他仍然可以解析其元素.我想处理MyClass中的添加和删除,提供一个AddChild(MyClass项目)和DeleteChild(MyClass项目),以确保在将一个项目添加到子级列表时,该项目的父级将被正确设置.

除了实现自己的IList之外,还有其他想法吗?

预先感谢,弗兰克

解决方案

如果将调用者交给 List< T> ,您将无法控制它.您甚至不能继承 List< T> 的子类,因为添加/删除不是 virtual .

然后,我将数据公开为 IEnumerable< MyClass> :

 私有只读列表< MyClass>children = new List< MyClass>();公共无效AddChild(MyClass child){...}公共无效RemoveChild(MyClass子级){...}公共IEnumerable< MyClass>孩子们 {得到 {foreach(孩子中的孩子)让孩子返回;}} 

(阻止他们进行投射)

呼叫者仍然可以在 .Children 上使用 foreach ,并且由于有了LINQ,他们也可以做所有其他有趣的事情( Where First 等).

in my C#-project, I have a class which contains a List

public class MyClass
{
  public MyClass parent;
  public List<MyClass> children;
  ...
}

I want to prevent the user of the class from Adding (and Deleting) an Element to the children-List, but he shall still be able to parse its elements. I want to handle the Adding and Deleting within MyClass, providing an AddChild(MyClass item) and DeleteChild(MyClass item) to ensure that, when an item is added to the child list, the parent of that item will be set properly.

Any idea how to do this besides implementing my own IList?

Thanks in advance, Frank

解决方案

If you hand the caller the List<T>, you can't control this; you can't even subclass List<T>, since the add/remove are not virtual.

Instead, then, I would expose the data as IEnumerable<MyClass>:

private readonly List<MyClass> children = new List<MyClass>();
public void AddChild(MyClass child) {...}
public void RemoveChild(MyClass child) {...}
public IEnumerable<MyClass> Children {
    get {
        foreach(var child in children) yield return child;
    }
}

(the yield return prevents them just casting it)

The caller can still use foreach on .Children, and thanks to LINQ they can do all the other fun things too (Where, First, etc).

这篇关于禁止对列表&lt; T&gt;进行公共添加和删除.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆