C#泛型 where约束

电玩女神 2022-06-18 01:12 361阅读 0赞

where(泛型类型约束)

定义:在定义泛型的时候,我们可以使用 where 限制参数的范围。

使用:在使用泛型的时候,你必须尊守 where 限制参数的范围,否则编译不会通过。

六种类型的约束:

T:类(类型参数必须是引用类型;这一点也适用于任何类、接口、委托或数组类型。)

  1. class MyClass<T, U>
  2. where T : class///约束T参数必须为“引用 类型{ }”
  3. where U : struct///约束U参数必须为“值 类型”
  4. { }

T:结构(类型参数必须是值类型。可以指定除 Nullable 以外的任何值类型。)

  1. class MyClass<T, U>
  2. where T : class///约束T参数必须为“引用 类型{ }”
  3. where U : struct///约束U参数必须为“值 类型”
  4. { }

T:new()(类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new() 约束必须最后指定。)

  1. class EmployeeList<T> where T : Employee, IEmployee, System.IComparable<T>, new()
  2. {
  3. // ...
  4. }

T:<基类名>(类型参数必须是指定的基类或派生自指定的基类。)

  1. public class Employee{}
  2. public class GenericList<T> where T : Employee

T:<接口名称>(类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。)

复制代码

  1. /// <summary>
  2. /// 接口
  3. /// </summary>
  4. interface IMyInterface
  5. {
  6. }
  7. /// <summary>
  8. /// 定义的一个字典类型
  9. /// </summary>
  10. /// <typeparam name="TKey"></typeparam>
  11. /// <typeparam name="TVal"></typeparam>
  12. class Dictionary<TKey, TVal>
  13. where TKey : IComparable, IEnumerable
  14. where TVal : IMyInterface
  15. {
  16. public void Add(TKey key, TVal val)
  17. {
  18. }
  19. }

复制代码

T:U(为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。也就是说T和U的参数必须一样

  1. class List<T>
  2. {
  3. void Add<U>(List<U> items) where U : T {
  4. /*...*/}
  5. }

一、可用于类:

  1. public class MyGenericClass<T> where T:IComparable { }

二、可用于方法:

  1. public bool MyMethod<T>(T t) where T : IMyInterface { }

三、可用于委托:

  1. 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

发表评论

表情:
评论列表 (有 0 条评论,361人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C# where约束

    [where(泛型类型约束)][where] 定义:在定义泛型的时候,我们可以使用 where 限制参数的范围。 使用:在使用泛型的时候,你必须尊守 where 限制参数的

    相关 约束

    要T是继承于A where T: A 要T继承于B的 where T: B 在定义泛型类时,可以对客户端代码能够在实例化类时用