• C#2.0 泛型


    1.泛型类

    定义:

    class Test<T> 注:T是占位符可以随便写
    {
          public T data; 注:定义一个T类型的字段
          public Test(T obj) 注:定义一个T类型的方法
          {
                 this.data = obj;
          }
    }

    实例化泛型类

    private static void Main(string[] args)
    {
    Test<int> test = new Test<int>(3); 
    Console.WriteLine(test.data);

    Console.ReadKey();
    }

    2.泛型方法

    定义:

    public static void Swap<T>(ref T a, ref T b)  值:定义一个泛型方法,ref 是指引用返回值是否作为调用方欲修改的引用被存储在本地
    {
          a = b;
    }

    private static void Main(string[] args)

    {

    int a = 1;
    int b = 2;
    Swap<int>(ref a, ref b); 注:传递int类型的两个值
    Console.Write(a);

    Console.ReadKey();
    }

     3.泛型约束

    public static void Swap<T>(ref T a, ref T b)  where T:struct 注:传递类型必须是值类型
    {
          a = b;
    }

    public static void Swap<T>(ref T a, ref T b)  where T:class注:传递类型必须是引用类型
    {
          a = b;
    }

    public static void Swap<T>(ref T a, ref T b)  where T:new()注:传递类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new() 约束必须最后指定。
    {
          a = b;
    }

    public static void Swap<T>(ref T a, ref T b)  where T:<基类名>注:传递类型参数必须是指定的基类或派生自指定的基类。
    {
          a = b;
    }

    public static void Swap<T>(ref T a, ref T b)  where T:<接口名称>注:传递类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。
    {
          a = b;
    }

    public static void Swap<T>(ref T a, ref T b)  where T:U  注:为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。这称为裸类型约束。
    {
          a = b;
    }

  • 相关阅读:
    when you try to reconfigure the BizTalk Server 2006 R2 EDI/AS2 Runtime feature
    Win7中发现的一个好东西
    WebMethod 处理 FlatFile
    BizTalk Http Adapter (BTSHttpReceive.dll) Error
    P1108 低价购买 DP
    Delete a Work Item Field from a Team Project Collection
    MCTS 70512: Unofficial Visual Studio Team Foundation Server 2010, Administration
    WEBGIS模型探讨
    TFS 2010 Red X on Work Items (TF51535)
    WIT: Field Name命名重复
  • 原文地址:https://www.cnblogs.com/zhang1999/p/7419517.html
Copyright © 2020-2023  润新知