泛型中的where

泛型的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()

例如:
    class Person<T> where T:class
    {
       
    }

    class Program
    {
        static void Main(string[] args)
        {
          
            Person<int> bb = new Person<int>(); //報錯,
错误 1 类型“int”必须是引用类型才能用作泛型类型或方法“ConsoleApplication1.Person<T>”中的参数“T” 

        }
    }

原文地址:https://www.cnblogs.com/annabook/p/2827166.html