在泛型上调用方法? [英] Invoke method on generic type?
问题描述
以下为什么在Delphi(XE)中产生错误?
Why does the following generate an error in Delphi (XE)?
unit UTest;
interface
type
TTest = class
public
procedure Foo<T>(A: T);
end;
implementation
{ TTest }
procedure TTest.Foo<T>(A: T);
begin
A.Add('hej');
end;
end.
我认为Delphi中的泛型类型只是插入到泛型函数中,因此只会出错
I thought that generic types in Delphi was simply inserted into the generic function, so it would only error out if used with a type which don't have an Add(string) method.
推荐答案
您的代码会产生编译错误,因为编译器无法知道 T
有一个名为 Add
的方法,该方法接收单个字符串参数。
Your code produces a compilation error because the compiler has no way of knowing that T
has a method named Add
that receives a single string parameter.
我认为Delphi中的泛型类型只是简单地插入到泛型函数中,因此,如果将其与不使用
I thought that generic types in Delphi was simply inserted into the generic function, so it would only error out if used with a type which don't have an Add(string) method.
如果您使用的是Smalltalk或C ++模板,则您的假设是正确的。但是,泛型与模板不同。对于泛型,您需要将约束应用于type参数。该约束需要告诉编译器 T
必须具有什么属性。
If you were using Smalltalk or C++ templates, then your assumption would be accurate. However, generics are not the same as templates. For generics you need to apply a constraint to the type parameter. The constraint needs to tell the compiler what properties T
must have.
例如,您可以约束 T
将从具有适当的 Add
方法的类派生。或者,您可以限制 T
来实现带有合适的 Add
方法的接口。
For example, you could constrain T
to be derived from a class that has a suitable Add
method. Or you could constrain T
to implement an interface with a suitable Add
method.
Delphi通用约束的文档链接: http://docwiki.embarcadero.com/RADStudio/en/Constraints_in_Generics
Documentation link for Delphi generic constraints: http://docwiki.embarcadero.com/RADStudio/en/Constraints_in_Generics
可以应用的通用约束相当有限,这实在令人遗憾。例如,我很希望能够将一个类型约束为具有某些数学运算符。例如,我希望能够将一个类型约束为具有 +
和-
运算符。但是,泛型和模板都各有利弊,因此,我确实接受这些限制是Delphi语言设计师做出合理设计决定的结果。
The generic constraints that can be applied are rather limited, which is something of a shame. For example, I'd love to be able to constrain a type to have certain mathematical operators. For example, I'd like to be able to constrain a type to have +
and -
operators, say. However, there are pros and cons to both generics and templates, and so I do accept that these limitations are the result of a justifiable design decision by the Delphi language designers.
这篇关于在泛型上调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!