• where用法


    where 子句用于指定类型约束。
     1.接口约束

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

     2.基类约束:

       指出某个类型必须将指定的类作为基类(或者就是该类本身),才能用作该泛型类型的类型参数。
       这样的约束一经使用,就必须出现在该类型参数的所有其他约束之前。

    class MyClassy<T, U>
     where T : class
     where U : struct
     {
     }

     3.构造函数约束
     new() 约束可以让编译器知道:提供的任何类型参数都必须具有可访问的无参数(或默认)构造函数。

    public class MyGenericClass <T> where T: IComparable, new()
    {
     // The following line is not possible without new() constraint:
     T item = new T();
    }

    4.还可以将约束附加到泛型方法的类型参数,例如:

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

    请注意,对于委托和方法两者来说,描述类型参数约束的语法是一样的:

    delegate T MyDelegate<T>() where T : new()
  • 相关阅读:
    C primer plus 摘抄(第三章 数据和C)
    lambda表达式+python内置函数
    补充(pass)
    If语句和while语句
    解释器和编译器的区别
    关于python编码
    初识Python
    unity学习(一)ide窗口
    unity学习
    redis实践 —— redisReply简析
  • 原文地址:https://www.cnblogs.com/sylone/p/7089958.html
Copyright © 2020-2023  润新知