Delphi 2009 泛型是如何工作的

术语泛型或泛类型(通用类型)描述了平台上的一组以类型作为参数化的事物。泛型可指泛类型和泛方法,如,泛过程和泛函数。

泛型是这样一组抽象工具,允许从一个或多个算法或数据结构用到的具体类型当中分离出算法(如过程或函数)或数据结构(如类,界面或记录)。

定义方法或数据类型时使用(以类型参数的方式,替换一个或多个具体类型)其他类型能可让(方法或数据类型)更加通用化。因此你可在方法或数据结构的声明里面添加那些类型参数到类型参数列表中。这类似于这样一些方式,在过程体中通过以参数名称来替换文字常量的实例,以及将参数添加到过程的参数列表中,这两种方式都可以让过程更加通用化。

例如,类(TMyList)维持了一组(TObject类型)的对象,以参数名称(如T)替换TObject,同时将类型参数添加到类的类型参数列表中(参数列表变成了TMyList<T>),这样类TMyList就增加了可重用性和类型-安全性。

泛类型或泛方法的具体实现(实例化),可通过在应用时向泛类型或泛方法提供类型参数(type arguments)。通过在泛型定义中以相应的类型参变量来替换类型参数的实例的动作可有效地构造出新的类型和方法。

举例,list有可能被用作TMyList<Double>类型。这将创建一个新的类型TMyList<Double>,除在定义中所有’T’实例被’Double’替换之外,其定义等同 TMyList<T>。

需要注意的是,作为抽象机制的泛型虽然重复了多态的许多功能,但是却有其特点。这是因为,所创建的新类型或方法是在实例化期间被创建的,这样, 你就可以很快在编译期间发现类型错误,而不是等到运行期间。这也增加了优化的范围,但是,每个实例化增加了最终应用程序的内存消耗,或许结果就是性能下降。

举例,TSIPair类包含了两个数据类型,String 和Integer:

 

 

type

      TSIPair = class

      private

      FKey: String;//具体的类型

      FValue: Integer;//具体的类型

      public

      function GetKey: String;

      procedure SetKey(Key: String);

      function GetValue: Integer;

      procedure SetValue(Value: Integer);

  //  property Key: TKey read GetKey write SetKey;//TKey – String

property Key: String read GetKey write SetKey;//

  //  property Value: TValue read GetValue write SetValue;

property Value: Integer read GetValue write SetValue;

      end;

创建数据类型独立类,用类型参数替换(具体)数据类型。

To make a class independent of data type, replace the data type with a type parameter.

 

type

// declares TPair type with two type parameters

     TPair<TKey,TValue{这是两个类型参数,说明有两个类型在这里,具体什么类型不知道}>= class  

      private

      FKey: TKey;//用一个未知类型的(有名字,没有具体类型)参数来定义一个变量

      FValue: TValue;

      public

      function GetKey: TKey;

      procedure SetKey(Key: TKey);

      function GetValue: TValue;

      procedure SetValue(Value: TValue);

      property Key: TKey read GetKey write SetKey;

      property Value: TValue read GetValue write SetValue;

      end;

     

      type

//下面在编译期间实例化TPair类,用具体的数据类型来替换先前的未知类型的类型参数,什么具体的类型都可以替换进来。但是,

//TPair类的成员,如procedure,function, property,variables 都可以不做改变。

      TSIPair = TPair<String,Integer>; // declares instantiated type,

      TSSPair = TPair<String,String>;  // declares with other data types

      TISPair = TPair<Integer,String>;

      TIIPair = TPair<Integer,Integer>;

      TSXPair = TPair<String,TXMLNode>;

posted on 2008-11-30 16:42  徐龠  阅读(774)  评论(0)    收藏  举报

导航