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

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

问题描述

我有一个类维护另一个类的对象列表。对象列表是一个公共属性。我想阻止用户直接添加和删除对象到列表,像这样:

  MyObject.MyListProperty.Add(object); 

而是我希望他们使用方法在内部做一些处理,然后添加对象到列表。 / p>

我有一些想法:




  • 创建 < T> 并覆盖添加和删除

  • 通过属性getter返回列表的新副本(列表相对较短,不超过30个对象) >


有没有添加和删除的收集界面?



编辑

我将使用 ReadOnlyCollection< T& code>。原因是包装的集合可以更新,并且更改将立即在只读对象中可见(请参阅 ReadOnlyCollection< T> AsReadOnly() )。这允许只创建一次只读列表。



IEnumerable 的问题是对象可以回复到原始 List< T>

您可以使用 http://msdn.microsoft.com/en-us/library/ms132474.aspxrel =nofollow noreferrer> ReadOnlyCollection - 将您的收藏包装在此并返回 ReadOnlyCollection 给你的类的用户:

  return new ReadOnlyCollection(innerCollection); 

或使用 AsReadOnly code> List< T> class:

  return innerCollection.AsReadOnly 

IEnumerable 接口将做你需要的,因为它只有一个成员 GetEnumerator() ,这只会让你遍历项目。


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.

I have some ideas:

  • 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)

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

Edit:
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.

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

解决方案

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

return new ReadOnlyCollection(innerCollection);

Or using the AsReadOnly method of the List<T> class:

return innerCollection.AsReadOnly();

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

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

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