zoukankan      html  css  js  c++  java
  • 泛型类定义 小小练习

     不需要引用其他单元文件,

    如果用泛型列表TList<T>或 字典TDictionary<TKey,TValue>时需要引用:System.Generics.Collections

    unit Unit1;
    
    interface
    uses System.Classes;
    type
      A = class //一般类
      end;
      B = class(A) //一般继承
      end;
      GB<T> = class(A) //继承于A的泛型类
      end;
      GC =class(GB<string>)//继承于GB<T>并指定T为 string的类  //值类型
      end;
      GD =class(GB<TStringList>)//继承于GB<T>并指定T为 TStringList的类  //引用类型
      end;
      GE=class(GB<A>)  //继承于GB<T>并指定T为 A的类 ;是自己的祖先类也可以吗?
      end;
      //-------------
      GH<T:A, constructor> =class  //一个直接的泛型类 T限定为A类 或A的子类
      end;
      J =class(GH<A>)
      end;
      k =class(GH<B>)
      end;
    //  L =class(GH<Int>) //会出错,因为 GH的类型限定 A或A的子类
    //  end;
      //----------------
      HttpAdpter =class
        procedure HTTPGetSync<T>(httpName: string); //泛型方法不一定写在泛型类里面
      end;
    implementation
    
    { HttpAdpter }
    
    procedure HttpAdpter.HTTPGetSync<T>(httpName: string);
    begin
    //方法体里面用到T,这里有疑问 ??  这个T应该从哪里传进去??
    end;
    
    end.

     =========================

    unit System.SysUtils; //单元中有定义下面的泛型方法 类型
    // Generic Anonymous method declarations
    type
      TProc = reference to procedure;
      TProc<T> = reference to procedure (Arg1: T);
      TProc<T1,T2> = reference to procedure (Arg1: T1; Arg2: T2);
    
      //----------以下应用 :用到两个 占位符,
    class procedure RunOnUIThread<T1, T2>(proc: TProc<T1, T2>; arg1: T1;
          arg2: T2); overload;
          
    class procedure TTask.RunOnUIThread<T1, T2>(proc: TProc<T1, T2>; arg1: T1;
    arg2: T2);
    begin
      Synchronize(TThread.CurrentThread,
        procedure()
        begin
          proc(arg1, arg2);
        end);
    end;

     上面用到两个 占位符,通过 RunOnUIThread<T1,T2>()参数传进去,并且前面要标明用到的 占位符,

     这个方法有点特殊,传了一个方法 proc: TProc<T1, T2> 进去

  • 相关阅读:
    腾讯云 Serverless 产品动态 20200827
    双指针 86. 分隔链表(链表 dummyhead)
    双指针:15. 三数之和
    双指针:283. 移动零
    双指针:167. 两数之和 II
    关于数组
    关于抽象类,接口以及多态
    关于字符串
    关于异常
    动手动脑3
  • 原文地址:https://www.cnblogs.com/rogge7/p/6567111.html
Copyright © 2011-2022 走看看