[英]How do I declare a variable of a generic type without knowing the type arguments?
How do I define a generic TList
type so that I can declare a variable of that type and then assign any specialization of TList<>
to it? 如何定义通用的
TList
类型,以便可以声明该类型的变量,然后为其分配TList<>
任何TList<>
?
I want to declare this variable: 我想声明这个变量:
var
MyList:THowToDeclareThisListType<T>;
And then instantiate it like this: 然后像这样实例化它:
MyList:=THowToDeclareThisListType<integer>.Create;
or 要么
MyList:=THowToDeclareThisListType<double>.Create;
etc. I must be missing something pretty obvious here. 等等。我一定在这里缺少一些显而易见的东西。 I don't want classes, just a simple type definition.
我不需要类,只是一个简单的类型定义。
You are trying to declare a variable like this: 您正在尝试声明这样的变量:
var
List: TList<?>;
such that List
can be assigned objects of type TList<Integer>
or TList<Double>
or TList<string>
. 这样就可以为
List
分配TList<Integer>
或TList<Double>
或TList<string>
类型的对象。
That is not possible. 这是不可能的。 When you define a variable using a generic type, the type must be fully instantiated.
使用泛型类型定义变量时,必须完全实例化该类型。
The only way that you can have a variable that holds any object of type TList<T>
is if the variable is declared to have a common base class to TList<T>
. 拥有包含
TList<T>
类型的任何对象的变量的唯一方法是,如果声明该变量具有TList<T>
的公共基类。 And the common base class cannot be a non-instantiated generic. 并且公共基类不能是非实例化的泛型。 For
TList<T>
the only possible common base class is TObject
. 对于
TList<T>
,唯一可能的公共基类是TObject
。
So you could write 所以你可以写
var
List: TObject;
and then assign any of your objects to List
. 然后将您的任何对象分配给
List
。 But I'm not sure that would be terribly useful! 但是我不确定这是否有用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.