Delphi:确定一个通用的实际类型? [英] Delphi: determine actual type of a generic?
问题描述
TSomeClass = class
procedure AddToList< T:TDataType; U:TListClass< T>(Element:T; List:U);
结束
与方法实现
procedure TSomeClass.AddToList< T,U>(Element:T; List:U);
begin
如果元素是TInt然后
List.AddElement(TInt.Create(XXX))
else如果元素是TString然后
List.AddElement(TString.Create (YYY));
结束
其中TInt.Create()和TString.Create()有不同的参数集,两者都继承自TDataType。
现在,我知道是
- 操作符不能这样使用,但是有没有一个合法的选择,我在这里问什么?
无法使用是操作符在这里是一个已知的问题,但有一个非常简单的解决方法。
如果TObject(Element)是TInt然后
List.AddElement(TInt.Create(XXX))
另外,由于通用是类的一部分,在编译时已知,您可能会更好地重组代码。制作两个不同的泛型类,其中一个类接受一个TInt作为其< T>
参数,另一个接受一个TString。将特定于类型的功能放入该级别的功能,并将它们从共同的祖先下载到共享功能。
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.
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?
Not being able to use the is operator here is a known issue, but there's a pretty simple workaround.
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. Put the type-specific functionality into them at that level, and have them descend from a common ancestor for shared functionality.
这篇关于Delphi:确定一个通用的实际类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!