【tag】C# where(泛型类型约束)
原文地址:C# where用法 , C# where用法解析 ,where(泛型类型约束)
where 子句用于指定类型约束,这些约束可以作为泛型声明中定义的类型参数的变量。
1.接口约束
public class MyGenericClass<T> where T:IComparable { }
2.基类约束
除以指出某个类型必须将指定的类作为基类(或者就是该类本身),才能用作该泛型类型的类型参数。 这样的约束一经使用,就必须出现在该类型参数的所有其他约束之前。
class MyClass<T, U> where T : class where U : struct { }
3.函数约束
可以使用 new 运算符创建类型参数的实例;但类型参数为此必须受构造函数约束 new() 的约束。 new() 约束可以让编译器知道:提供的任何类型参数都必须具有可访问的无参数(或默认)构造函数。
public class MyGenericClass<T> where T : IComparable, new() { // The following line is not possible without new() constraint: T item = new T(); }
new() 约束出现在 where 子句的最后。
对于多个类型参数,每个类型参数都使用一个 where 子句
interface IMyInterface { } class Dictionary<TKey, TVal> where TKey : IComparable, IEnumerable where TVal : IMyInterface { public void Add(TKey key, TVal val) { } }
4.泛型方法的类型参数约束
public bool MyMethod<T>(T t) where T : IMyInterface { }
请注意,对于委托和方法两者来说,描述类型参数约束的语法是一样的:
delegate T MyDelegate<T>() where T : new()
总结:
泛型的Where能够对类型参数作出限定。有以下几种方式:
where T : struct 限制类型参数T必须继承自System.ValueType。
where T : class 限制类型参数T必须是引用类型,也就是不能继承自System.ValueType。
where T : new() 限制类型参数T必须有一个缺省的构造函数
where T : NameOfClass 限制类型参数T必须继承自某个类或实现某个接口。
以上这些限定可以组合使用,比如: public class Point where T : class, IComparable, new()
浙公网安备 33010602011771号