Delphi 通用类型 - 特异性?
我正在尝试在 delphi 下创建一个名为 TRange 的通用类。这个想法是,它可以是一个整数范围或一个单精度范围、或双精度范围等...
TRange 对象包含一些 T 类型的变量(maxValue、minValue、idealValue 等)。 TRange 包含每个函数将它们转换为字符串的函数。然而,由于 Delphi 是一种强类型语言,我需要指定“如何”将不同的变量转换为字符串。
我可以使用 GetTypeName (TypeInfo (T)) 获取 T 类型的 typeName。一旦我知道哪种类型是 T,我想我可以做类似的事情:
if(className = 'single') then
result := formatFloat('0.0', self.AbsMin as Single)
else
result := intToStr(self.AbsMin as Integer)
但是,编译器告诉我“运算符不适用于此操作数类型”。
所以,我想我的问题是:
有没有办法赋予通用类特殊性???
I am trying to create a generic class under delphi called TRange. The idea is that it can be a Range of Integer or a range of single, or Double, etc...
The TRange object contains a few variables of type T (maxValue, minValue, idealValue, etc). The TRange contains a function for each of them to convert them into a string. However, since Delphi is a strong-typed language, I need to specify "How-To" convert the different variables into a string.
I can get the typeName of the T type using GetTypeName (TypeInfo (T)). Once I know which type is T, I thought I could do something like:
if(className = 'single') then
result := formatFloat('0.0', self.AbsMin as Single)
else
result := intToStr(self.AbsMin as Integer)
However, the compiler tells me "Operator not Applicable to this operand Type".
So, I guess my question is :
Is there a way to give specificity to a generic Class???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编译器错误源自以下事实:您无法使用
as
运算符强制转换为基本类型,例如Single
或Integer
。为此使用硬转换:Single(AbsMin)
。为什么需要将值转换为字符串?这有点违背泛型类的想法,因为您现在又要为所有情况实现特殊行为。
如果你确实需要这个,你可以引入一个接口
你可以在 TRange 类的构造函数中提供转换器并将其存储在一个字段中:
现在只需使用类内的转换器来进行转换:
The compiler error comes from the fact that you cannot use the
as
operator to cast to a primitive type such asSingle
orInteger
. Use a hard cast for that:Single(AbsMin)
.Why do you need to convert the values to strings? This is kind of against the idea of a generic class, because you are now back to implementing special behaviour for all the cases.
If you really need this though you could introduce an interface
You can just supply the converter in the constructor of the
TRange
class and store it in a field:Now just use the converter inside the class to do the conversion: