使用.NET泛型集合(Generic Collection)
发表于2008年12月23日StackOverflow上看到一个关于泛型类型检查的问题。
定义一个泛型类时,可以使用where关键字对初始化时用做类型参数(type arguments)的类型加以约束(constraints )。如果不符合约束则抛出编译时错误(compile-time error)。
支持的约束有:
| 约束 | 描述 |
|---|---|
| where T : struct | 类型参数必须是值类型。除了Nullable。 |
| where T : class | 类型参数必须是引用类型,包括类、接口、委托和数组。 |
| where T : new() | 类型参数必须包含一个公共的无参构造函数,这个约束必须放在所有的其他约束之后。 |
| where T : <base_class_name> | 类型参数必须是此基类或者此基类的派生类 |
| where T : <interface_name> | 类型参数必须实现指定接口,可以指定多接口,或者泛型接口。 |
| where T : U | T的类型参数必须是U,或者U的类型参数派生类。所谓裸类型约束(naked type constraint)。 |
.NET泛型支持,泛型参数,泛型接口,泛型方法等。Code Project上一篇讲解.Net泛型集合的文章。
C5项目
CollectionBase应该是Java中的Set,是众多集合的基类。
Java集合与C5集合对比
| Java中的 | C5中的 |
|---|---|
| java.util.Set | C5.CollectionBase |
| java.util.HashSet | C5.HashSet |
| java.util.List | C5.IList |
| java.util.TreeSet | C5.TreeSet |
| java.util.Collection | C5.ICollection |
| java.util.Map | C5.IDictionary |
使用1:
Set newHead = new HashSet();
使用2:
Map head = new HashMap(); for (Collection entries : head.values()) { // ... }
使用3:
public static List asList(T... a) { return new ArrayList(a); }