[英]How do I implement a generic class that has an constraint for a generic interface?
I have an Interface 我有一个界面
IMyInterface<T>
and a class 和一堂课
TMyClass<T>
and now I want that I can only pass classes to TMyClass as a type, that also implement IMyInterface. 现在我希望只能将类作为类型传递给TMyClass,该类也实现IMyInterface。
First I tried 首先我尝试
TMyClass<T:IMyInterface<T>>
but as expected, now the compiler wants me to give him a type which implements an interface with the type of class itself that implements the interface 但是正如预期的那样,现在编译器要我给他一个实现接口的类型,以及实现该接口的类本身的类型
Second try was 第二次尝试是
TMyClass<D,T:IMyInterface<D>>
where I thought, D would then be the shared DataType, both TMyInterface and TMyClass would use. 我以为,D将成为共享数据类型,TMyInterface和TMyClass都将使用。
So after declaring the class implementing the interface 所以在声明实现接口的类之后
TMyIntegerClass = class(TInterfacedObject,IMyInterface<Integer>)
The declaration 报关单
GMyClass:TMyClass<Integer,TMyIntegerClass>
failed with compiler error: 因编译器错误而失败:
E2514 Type parameter 'D' must support interface 'IMyInterface<System.Integer>'
Any pointers? 有指针吗?
This compiles in Delphi 10.2.2 Tokyo: 它将在Delphi 10.2.2 Tokyo中编译:
type
IMyInterface<T> = interface
['{F810B6BC-78F7-4026-BA83-70435150B758}']
end;
TMyClass<D; T: IMyInterface<D>> = class // note the semicolon!
end;
TMyIntegerClass = class(TInterfacedObject, IMyInterface<Integer>)
end;
var
GMyClass: TMyClass<Integer, TMyIntegerClass>;
If, in the declaration of the class , I use <D, T: TSomeType>
(comma!) then both D
and T
are declared to be of the same type , like parameters of a function: 如果在类的声明中使用
<D, T: TSomeType>
(逗号!),则D
和T
都声明为同一类型 ,例如函数的参数:
procedure Blah(D, T: TSomeType);
Parameters D
and T
are of the same type, ie TSomeType
. 参数
D
和T
具有相同的类型,即TSomeType
。
Now, if you pass an Integer
for D
, you get an error, similar to the one you got. 现在,如果为
D
传递一个Integer
,则会得到一个错误,类似于您得到的错误。 The compiler expects two TSomeType
parameters. 编译器需要两个
TSomeType
参数。
But if I use <D; T: TSomeType>
但是如果我使用
<D; T: TSomeType>
<D; T: TSomeType>
then D
and T
are separate types , ie D
is of an unknown type and T
is of type TSomeType
. <D; T: TSomeType>
然后D
和T
是单独的类型 ,即D
是未知类型, T
是TSomeType
类型。 So now, D
is not declared as TSomeType
and there is no error if you pass Integer
. 因此,现在
D
不声明为TSomeType
并且如果您传递Integer
则没有错误。
Oh, and this is documented too . 哦, 这也有记录 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.