zoukankan      html  css  js  c++  java
  • where泛型约束

    where用于指定类型约束,这些约束可以作为泛型声明中定义的类型参数的变量.如下:
    public class MyGenericClass<T> where T:IComparable { }
      除了接口约束,where还可以包括基类约束,以指出某个类型必须将指定的类作为基类(或者就是该类本身),才能用作该泛型的类型参数.如下:
    class MyClassy<T, U>
        where T : class
        where U : struct
    {
    }
      where还可以包括构造函数约束,可以使用new运算符创建类型参数的实例;但类型参数必须受构造函数约束new()的约束.new()约束可以让编译器知道:提供的任何类型参数都必须具有可访问的无参数构造函数,如下:
    public class MyGenericClass <T> where T: IComparable, new()
    {
        // The following line is not possible without new() constraint:
        T item = new T();
    }
       对于多个类型参数,每个类型参数都使用一个where,例如:
    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 { }
       注意:对于委托和方法两者来说,描述类型参数约束的语法是一样的:
    delegate T MyDelegate<T>() where T : new()
  • 相关阅读:
    ES6 数组下
    ES6 ---数组(上部分)
    ES6---函数
    ES6---字符串
    自适应网页设计(Responsive Web Design)
    HTML Meta中添加X-UA-Compatible和IE=Edge,chrome=1有什么作用?
    mysql潜在的危险kill
    shell脚本加密
    Linux安全知识总结
    nginx 解决400 bad request 的方法(转载)
  • 原文地址:https://www.cnblogs.com/mrhgw/p/777368.html
Copyright © 2011-2022 走看看