两个不同的子类型继承相同记录助手

5

当一个类型声明有两个派生自同一内部类型的子类型时,我们如何为每个子类型拥有不同的记录辅助函数呢?

例如:

type
  SingleA = Single;
  SingleB = Single;

  _SingleA = record helper for SingleA
    procedure DoThingsToA;  
  end;

  _SingleB = record helper for SingleB
    procedure DoThingsToB;  
  end;

如果我声明一个类型为SingleA的变量,我总是会得到来自类型SingleB的帮助程序,如果我们覆盖相同的内部类型,我知道这是正常行为,但为什么不同类型也会发生这种情况呢?
非常感谢任何帮助...
提前致谢。
2个回答

7

在这里你没有声明子类型。这段代码:

type
  SingleA = Single;
  SingleB = Single;

仅仅是声明别名,而不是类型。因此,SingleASingleB实际上是相同的类型Single

这在这里解释:

类型兼容性和标识(Delphi)

When one type identifier is declared using another type identifier, without qualification, they denote the same type. Thus, given the declarations:

type
  T1 = Integer;
  T2 = T1;
  T3 = Integer;
  T4 = T2;

T1, T2, T3, T4, and Integer all denote the same type. To create distinct types, repeat the word type in the declaration. For example:

type TMyInteger = type Integer;

creates a new type called TMyInteger which is not identical to Integer.

实际上,= type x 构造为类型创建了新的类型信息,从而使 TypeInfo(SingleA) <> TypeInfo(SingleB)
在您的原始代码中,您只是为同一类型 Single 声明了两个别名。
对于任何给定类型(及其别名),您可以 在作用域中仅有一个类型辅助程序,因此在您的原始代码中,record helper for SingleB 隐藏了 record helper for SingleA
通过将别名升级为它们自己的类型,您避免了这个问题:
type
  SingleA = type Single;    
  SingleB = type Single;  <<-- the type keyword makes SingleB distinct from SingleA

现在你将拥有两种不同的类型,并且你的记录助手将按预期工作。

非常感谢您,Johan,您已经让它变得清晰明了! - António Cálix

1
很抱歉,当你声明时,保留html,不要解释。
type
   SingleA = Single;

Delphi将此视为别名而不是派生类型。
因此,在您的情况下,SingleA、SingleB和Single都被视为相同。 (您可以通过声明具有SingleA类型参数的函数并尝试将SingleB参数传递给它来查看此内容)。
因此,遵循任何一种类型只能有一个辅助程序的规则,并且SingleB的辅助程序是最后定义的,那么正如您所评论的那样,这种行为是可以预期的。
编辑
您还可以通过逐步执行代码并查看本地变量窗口中类型为SingleA或SingleB的变量的参数类型来查看此内容。例如。 您会发现它始终被指定为类型Single。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接