where(泛型类型约束)
2017-06-29 01:03
363 查看
定义:在定义泛型的时候,我们可以使用 where 限制参数的范围。
使用:在使用泛型的时候,你必须尊守 where 限制参数的范围,否则编译不会通过。
六种类型的约束:
T:类(类型参数必须是引用类型;这一点也适用于任何类、接口、委托或数组类型。)
T:结构(类型参数必须是值类型。可以指定除 Nullable 以外的任何值类型。)
T:new()(类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new() 约束必须最后指定。)
T:<基类名>(类型参数必须是指定的基类或派生自指定的基类。)
T:<接口名称>(类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。)
可用于类、方法、委托
当只希望传过来的泛型参数是限定范围的,需要用到 WHERE 来限定
比如希望是值类型,或者是引用类型,或者是继承至某个类型、或者是符合某个接扣的类型,
参考文档:
https://msdn.microsoft.com/zh-cn/library/d5x73970.aspx https://msdn.microsoft.com/zh-cn/library/bb384067.aspx
使用:在使用泛型的时候,你必须尊守 where 限制参数的范围,否则编译不会通过。
// .NET支持的类型参数约束 : //where T : struct | T必须是一个结构类型 //where T : class | T必须是一个Class类型 //where T : new() | T必须要有一个无参构造函数 //where T : NameOfBaseClass | T必须继承名为NameOfBaseClass的类 //where T : NameOfInterface | T必须实现名为NameOfInterface的接口
六种类型的约束:
T:类(类型参数必须是引用类型;这一点也适用于任何类、接口、委托或数组类型。)
class MyClass<T, U> where T : class///约束T参数必须为“引用 类型{ }” where U : struct///约束U参数必须为“值 类型” { }
T:结构(类型参数必须是值类型。可以指定除 Nullable 以外的任何值类型。)
class MyClass<T, U> where T : class///约束T参数必须为“引用 类型{ }” where U : struct///约束U参数必须为“值 类型” { }
T:new()(类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new() 约束必须最后指定。)
class EmployeeList<T> where T : Employee, IEmployee, System.IComparable<T>, new() { // ... }
T:<基类名>(类型参数必须是指定的基类或派生自指定的基类。)
public class Employee{} public class GenericList<T> where T : Employee
T:<接口名称>(类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。)
/// <summary> /// 接口 /// </summary> interface IMyInterface { } /// <summary> /// 定义的一个字典类型 /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TVal"></typeparam> class Dictionary<TKey, TVal> where TKey : IComparable, IEnumerable where TVal : IMyInterface { public void Add(TKey key, TVal val) { } }
T:U(为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。也就是说T和U的参数必须一样)
class List<T> { void Add<U>(List<U> items) where U : T {/*...*/} }
可用于类、方法、委托
public class MyGenericClass<T> where T:IComparable { } public bool MyMethod<T>(T t) where T : IMyInterface { } delegate T MyDelegate<T>() where T : new()
当只希望传过来的泛型参数是限定范围的,需要用到 WHERE 来限定
比如希望是值类型,或者是引用类型,或者是继承至某个类型、或者是符合某个接扣的类型,
参考文档:
https://msdn.microsoft.com/zh-cn/library/d5x73970.aspx https://msdn.microsoft.com/zh-cn/library/bb384067.aspx
相关文章推荐
- c# 泛型T类型参数T的约束where
- 关于C#中泛型类型参数约束(where T : class)
- where T : class泛型类型约束
- c# 泛型类型参数T的约束where
- C#关键字-where(泛型类型约束)
- c#泛型类型的约束条件where
- 关于where(泛型类型约束)
- where 泛型类型约束 default 关键字
- where 泛型类型约束 default 关键字
- where(泛型类型约束)
- where T:class 泛型类型约束
- C# 泛型类型约束 where
- 泛型类型参数约束 <T> where T : class,new(){}
- where T : class泛型类型约束
- 使用 where 子句约束泛型类型
- c#中的WHERE语句 ——where(泛型类型约束)
- c# where(泛型类型约束)
- where(泛型类型约束)(C# 参考)
- 泛型约束where条件的使用(通过类型参数动态反射创建实例)
- 【C#】C#关键字-where(泛型类型约束)