简体   繁体   English

在泛型类型上调用方法?

[英]Invoke method on generic type?

Why does the following generate an error in Delphi (XE)? 为什么以下在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.

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. 我认为Delphi中的泛型类型只是简单地插入到泛型函数中,因此如果使用没有Add(string)方法的类型,它只会出错。

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. 您的代码产生编译错误,因为编译器无法知道T有一个名为Add的方法接收单个字符串参数。

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. 我认为Delphi中的泛型类型只是简单地插入到泛型函数中,因此如果使用没有Add(string)方法的类型,它只会出错。

If you were using Smalltalk or C++ templates, then your assumption would be accurate. 如果您使用的是Smalltalk或C ++模板,那么您的假设将是准确的。 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必须具有哪些属性。

For example, you could constrain T to be derived from a class that has a suitable Add method. 例如,您可以将T约束为从具有合适Add方法的类派生。 Or you could constrain T to implement an interface with a suitable Add method. 或者您可以约束T以使用合适的Add方法实现接口。

Documentation link for Delphi generic constraints: http://docwiki.embarcadero.com/RADStudio/en/Constraints_in_Generics Delphi通用约束的文档链接: http//docwiki.embarcadero.com/RADStudio/en/Constraints_in_Generics

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. 但是,泛型和模板都有利弊,因此我接受这些限制是德尔福语言设计师做出合理设计决策的结果。

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

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