是否有prevents添加对象一个.NET集合接口? [英] Is there a .NET collection interface that prevents adding objects?

查看:131
本文介绍了是否有prevents添加对象一个.NET集合接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有一个维护另一个类的对象列表的类。对象列表是公共财产。我想prevent用户添加,直接删除对象,列出这样的:

I have a class that maintains list of objects of another class. List of objects is a public property. I would like to prevent users from adding and removing objects directly to list like this:

      MyObject.MyListProperty.Add(object);

相反,我希望他们使用的方法,这将在内部做一些处理,然后添加对象列表中。

Instead I want them to use method that will internally do some processing and then add object to list.

我有一些想法:

  • 创建名单,其中的后裔; T> 并覆盖添加和删除
  • 通过属性getter返回列表的新副本(列表比较短,不超过30个对象)
  • create descendant of List<T> and override add and remove
  • return fresh copy of list through property getter (list is relatively short, not more than 30 objects)

有没有办法,没有添加和删除一些Collection接口?

Is there some collection interface that does not have Add and Remove?

编辑:
我会去与 ReadOnlyCollection还&LT; T&GT; 。原因是包装的集合进行更新和变化将是只读对象立即可见(请参阅<一个MSDN code例子href="http://msdn.microsoft.com/en-us/library/ms132474.aspx"><$c$c>ReadOnlyCollection<T> AsReadOnly() )。这允许只读列表创建一次。


I'm going to go with ReadOnlyCollection<T>. Reason is that wrapped collection can be updated and changes will be immediately visible in read only object (see MSDN code examples for ReadOnlyCollection<T> and AsReadOnly()). This allows that read only list be created only once.

的IEnumerable 的问题是,对象可以被转换回原来的名单,其中,T&GT; ,然后 直接操作。

The problem with IEnumerable is that object can be casted back to original List<T> and then directly manipulated.

推荐答案

您可以使用 ReadOnlyCollection还 - 包装您的收藏在此,返回 ReadOnlyCollection还来类的用户:

You can use ReadOnlyCollection - wrap your collection in this and return the ReadOnlyCollection to users of your class:

return new ReadOnlyCollection(innerCollection);

或者使用的 AsReadOnly 方法名单,其中,T&GT; 类:

return innerCollection.AsReadOnly();

借助的IEnumerable 界面会做你的需要,因为它只有一个成员的GetEnumerator(),那样只会让你遍历项目。

The IEnumerable interface will do what you need, as it only has one member GetEnumerator(), that will only let you iterate over items.

这篇关于是否有prevents添加对象一个.NET集合接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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