【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
接口约束
public class MyGenericClass<T> where T:IComparable { }
基类约束:指出某个类型必须将指定的类作为基类(或者就是该类本身),才能用作该泛型类型的类型参数。这样的约束一经使用,就必须出现在该类型参数的所有其他约束之前。
class MyClassy<T, U>
where T : class
where U : struct
{
}
- where 子句还可以包括构造函数约束。
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 MyI { }
class Dictionary<TKey,TVal>
where TKey: IComparable, IEnumerable
where TVal: MyI
{
public void Add(TKey key, TVal val)
{
}
}
将约束附加到泛型方法的类型参数
public bool MyMethod<T>(T t) where T : IMyInterface { }
泛型的Where 泛型的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()
来源:oschina
链接:https://my.oschina.net/stupidpotato/blog/3154510