基于泛型类的具体类型的条件行为

基于泛型类的具体类型的条件行为

本文介绍了基于泛型类的具体类型的条件行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我昨天在 提出的问题可能并不完全清楚,我也没有得到答案我想要,我会尝试以更一般的方式来表述它:

Since my question from yesterday was perhaps not completely clear and I did not get the answer I wanted, I will try to formulate it in a more general way:

有没有办法基于实例化泛型类型的实际类型使用显式条件语句或使用某种特殊化来实现特殊行为?伪代码:

Is there a way to implement special behaviour based on the actual type of an instantiated generic type either using explict conditional statements or using some kind of specialization? Pseudocode:

TGenericType <T> = class
  function Func : Integer;
end;
...
function TGenericType <T>.Func : Integer;
begin
  if (T = String) then Exit (0);
  if (T is class) then Exit (1);
end;
...
function TGenericType <T : class>.Func : Integer;
begin
Result := 1;
end;
function TGenericType <String>.Func : Integer;
begin
Result := 0;
end;

推荐答案

您可以使用 TypeInfo(T) = TypeInfo(string) 回退到 RTTI.要测试某个东西是否是一个类,您可以使用类似 PTypeInfo(TypeInfo(T))^.Kind = tkClass.

You can fall back to RTTI, by using TypeInfo(T) = TypeInfo(string). To test to see if something is a class, you could use something like PTypeInfo(TypeInfo(T))^.Kind = tkClass.

PTypeInfo 类型和 tkClass 枚举成员在 TypInfo 单元中定义.

The PTypeInfo type and tkClass enumeration member are defined in the TypInfo unit.

这篇关于基于泛型类的具体类型的条件行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 19:19