简体   繁体   English

Delphi:确定通用的实际类型?

[英]Delphi: determine actual type of a generic?

Is there any way to determine the type of a variable passed as an argument to a method? 有没有办法确定作为方法参数传递的变量的类型? Consider the class: 考虑班级:

TSomeClass = class
  procedure AddToList<T: TDataType; U: TListClass<T>>(Element: T; List: U);
end;

with the method implementation 与方法实现

procedure TSomeClass.AddToList<T, U>(Element: T; List: U);
begin
  if Element is TInt then
    List.AddElement(TInt.Create(XXX))
  else if Element is TString then
    List.AddElement(TString.Create(YYY));
end;

where TInt.Create() and TString.Create() have different sets of arguments, yet, they both inherit from TDataType. 其中TInt.Create()和TString.Create()具有不同的参数集,但它们都继承自TDataType。

Now, I know the is -operator can't be used like this, but is there a legal alternative that does what I'm asking here? 现在,我知道is -operator不能像这样使用,但是有没有合法的替代品可以做我在这里问的问题?

Not being able to use the is operator here is a known issue, but there's a pretty simple workaround. 这里无法使用is运算符是一个已知问题,但有一个非常简单的解决方法。

  if TObject(Element) is TInt then
    List.AddElement(TInt.Create(XXX))

Also, since the type of a generic is part of the class and is known at compile-time, you might be better off restructuring your code. 此外,由于泛型的类型是类的一部分并且在编译时是已知的,因此您可能最好重构代码。 Make two different generic classes, one of which accepts a TInt as its <T> parameter, and the other of which accepts a TString. 创建两个不同的泛型类,其中一个接受TInt作为其<T>参数,另一个接受TString。 Put the type-specific functionality into them at that level, and have them descend from a common ancestor for shared functionality. 在特定级别将特定于类型的功能放入其中,并让它们从共同的祖先下降以获得共享功能。

This question I asked some time ago 我前段时间问过这个问题

Conditional behaviour based on concrete type for generic class 基于泛型类的具体类型的条件行为

might be of interest, especially if you want to use not only TObject descendants but also primitive types in your conditionals. 可能是有意义的,特别是如果你不仅要使用TObject后代,还要使用条件中的原始类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM