简体   繁体   English

变体记录而不是重载的 object 类型?

[英]Variant record instead of overloaded object type?

I'm working on a problem in which I need to dynamically size an array, upon which numerous operations are needed.我正在解决一个需要动态调整数组大小的问题,在这个问题上需要大量操作。 I have successfully coded two classes, t_one and t_two:我已经成功编写了两个类,t_one 和 t_two:

tarray1 : array of longint;
tarray2 : array of single;
t_one = class(tobject)
  Public
  Myarray1 : tarray1;
  constructor create;
  destructor destroy;
  procedure oneofmany; 
end;
t_two = class(tobject)
  Public
  Myarray1 : tarray2;
  constructor create;
  destructor destroy;
  procedure oneofmany; 
end;

The two objects have nearly identical code except that Myarray1 is an array of single in one case and an array of longint in the other.这两个对象的代码几乎相同,只是 Myarray1 在一种情况下是 single 数组,而在另一种情况下是 longint 数组。 Is the only way to make this into a single object to use variant arrays (which will slow things down)?将其制成单个 object 以使用变体 arrays 的唯一方法是(这会减慢速度)吗? A variant record is inefficient for what I'm doing as well.变体记录对于我正在做的事情也是低效的。 If I could say如果我能说

case mysituation of
  integerdata : (myarray1 : tarray1);
  realdata: (myarray1 : tarray2);
end;

that would be what I mean, but obviously that syntax is anathema.这就是我的意思,但显然这种语法是诅咒。 Of course, there are places where method calls and function results need to know the data type, but once defined they're consistent.当然,有些地方方法调用和 function 结果需要知道数据类型,但是一旦定义它们是一致的。 Thoughts?想法? Use a variant array and suffer the slowdown?使用变体数组并遭受减速?

One of possible approaches - make the only class using generics一种可能的方法 - 使用 generics 制作唯一的 class

  TA<T> = class
  public
     Arr : TArray<T>;
     destructor destroy;override;
  end;
...
procedure TForm1.Button1Click(Sender: TObject);
var
  A: TA<Integer>;
  B: TA<Single>;
begin
  A := TA<Integer>.Create;
  B := TA<Single>.Create;
  A.Arr := [1,2,3];
  B.Arr := [Pi, Ln(2)];
  Memo1.Lines.Add(A.Arr[0].ToString);
  Memo1.Lines.Add(B.Arr[0].ToString);
end;

Turns out the answer leads to solutions that get quite convoluted.事实证明,答案会导致解决方案变得非常复杂。 There's a reason for strong typing, Because one cannot have multiple function return types with the same function name.强类型是有原因的,因为不能有多个 function 返回类型具有相同的 function 名称。 one gets bogged down in similarly named functions for different argument types.对于不同的参数类型,人们陷入了类似命名的函数中。 If you try如果你试试

var
  mypointer : pointer;
begin
  case argtype of
    integer: mypointer := @A;
    single : mypointer := @B;
end;

then you still need to type mypointer every time you use it.那么你每次使用它时仍然需要输入 mypointer 。 Turns out not to help a whole lot.事实证明并没有太大帮助。

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

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