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

问题描述

由于我的问题从可能并不完全清楚,我没有得到答案我想,我会尝试以更一般的方式来制定它:

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;


推荐答案

您可以回到RTTI,使用 TypeInfo(T)= TypeInfo(string)。要测试某些东西是否是一个类,可以使用类似于 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.

TypInfo中定义了 PTypeInfo 类型和 tkClass 枚举成员单位。

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

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

09-25 19:37