是否有.NET是prevent空条目任何收藏? [英] Are there any collections in .NET that prevent null entries?

查看:97
本文介绍了是否有.NET是prevent空条目任何收藏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我特别想,满足一组契约的集合,但我认为这个问题可以适用于任何类型的。有没有在.NET框架prevent空条目的集合?我想具体的行为是这样的:

I'm specifically thinking about a collection that fulfills the contract of a set, but I think the question can apply to any kind. Are there collections in the .NET framework that prevent null entries? The specific behavior I want is this:

var set = new HashSet<object>();
bool added = set.Add(null);
Console.WriteLine(added); // prints "False"

这是不是内置的的HashSet 1所述的行为; T&GT; 。是否有确实有这个(或类似)的行为有任何的集合,还是我最好滚动我自己?如果是后者,什么是去了解它的最好方法是什么?我应该直接继承自的HashSet&LT; T&GT; 或只是把它包

This isn't the behavior of the built-in HashSet<T>. Are there any collections that do have this (or similar) behavior, or am I better off rolling my own? If the latter, what's the best way to go about it? Should I inherit directly from HashSet<T> or just wrap it?

编辑:要清楚,这仅仅是闲置的疑惑。主要是因为我想不出任何理由我会永远的需要的允许成一组对象。我没有这个任何特定的需求。

To be clear, this is just idle wondering. Mostly because I can't think of any reason I'd ever want to allow null into a set of objects. I don't have any particular need for this.

推荐答案

没有一个内置类,就像的HashSet&LT; T&GT; 除了这个单一的行为

There isn't a built-in class just like HashSet<T> except for this single behavior.

如果你需要,我建议你滚动您自己。我不建议子类化的HashSet&LT; T&GT; ,但是。没有一种方法(如添加,其中要明确改变)是虚拟的,因为它是不是真的设计子类的初衷。这将导致奇怪的使用行为,因为你会隐藏继承的方法。

If you need this, I'd recommend rolling your own. I do not recommend subclassing HashSet<T>, however. None of the methods (like Add, which you explicitly want to change) are virtual, as it wasn't really designed with subclassing in mind. This will cause strange usage behavior, since you'd be hiding the inherited methods.

只是封装了的HashSet&LT; T&GT; ,并揭露你所需要的成员。唯一真正的code你必须补充的是,在添加方法单一空检查 - 否则,只是通过所有的方法来封装实例

Just encapsulate a HashSet<T>, and expose the members you need. The only real "code" you'd have to add is a single null check on the Add method - otherwise, just pass through all of the methods to the encapsulated instance.

如果你想这是一个通用类,你需要一个额外的约束添加到唯一的工作带班,因为你想有一个空检查:

If you want this to be a generic class, you'll need to add an extra constraint to only work with classes, since you want to have a null check:

public class ValueSet<T> : ICollection<T>, IEnumerable<T>, ICollection
    where T : class
{
     private HashSet<T> hashSet = new HashSet<T>();
     // ... Implement all members as needed...

这篇关于是否有.NET是prevent空条目任何收藏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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