Var
     A : Array [1..4] of Integer;
     B : Array [1..4] of Integer;

Begin
    A := B;

不会正如洛伦·佩奇特(Loren-Pechtel)所说的 这里问题是A和B对我来说是不同的单位。那么,是否有一种方法可以从另一类中的现有定义定义类型定义?

有帮助吗?

解决方案

定义某个单元的接口块中的类型,然后通过 uses 您需要该类型的其他单元中的子句。

unit A;
interface
type
  TMyArray = array [1..4] of Integer;

...

当您需要使用时 TMyArray 在另一个单元中:

unit B;
interface
uses A;

...
var x : TMyArray;

其他提示

或者,在单元C的接口部分中定义您的类型,并在A和B中使用此单元。

Delphi中的数组类型有些奇怪。它 看起来 像A和B一样,类型完全相同,但Delphi并不认为它们是相同的。 “整数的数组[1..4]出现了两次,因此Delphi认为有两种不同的类型。那只是德尔菲的奇怪性。我认为,大多数其他语言都不会在乎。在实践中,这不是问题;有点奇怪。也许有充分的理由。谁知道。正如其他人所说,该解决方案是定义您自己的类型的,您可以将其放入其他单位可以使用的单元中。我只是提到这个阵列类型的问题,因为它可能使您感到困惑。

另一种方法是有点老式的,但仍然有效,是使用绝对的关键字迫使一个人的记忆叠加另一个类型,并使另一种类型兼容。例如,在A单元中,您有以下内容:

TYPE
  TArrayA = Array[1..4] of integer;

然后在B单元中,您有以下内容:

TYPE
  TArrayB = Array[1..4] of integer;  

为了兼容,您可以执行以下操作:

VAR
  InstanceA : TArrayA;
  InstanceB : TArrayB;
  InstanceBasA : TArrayA ABSOLUTE InstanceB;

这样做的是创建一个类型Arraya的变量“ InstanceBasa”,该变量与变量“ InstanceB”叠加相同的内存空间。这使您可以执行以下命令:

InstanceA := InstanceBasA;

将数据从变量布移到变量B的另一种方法是使用MOVE命令。例如,要从Arraya移动到ArrayB,您可以执行以下操作:

var
  ArrayA : array[1..4] of Integer;
  ArrayB : Array[1..4] of Integer;
begin
  FillChar(ArrayB[1],SizeOf(ArrayB),#0);
  ArrayA[1] := 1234;
  ArrayA[2] := 3456;
  ArrayA[3] := 7890;
  ArrayA[4] := 9876;

  // This is where the move from ArrayA to ArrayB happens.
  Move( ArrayA[1], ArrayB[1], SizeOf(ArrayA) );

  Assert( ArrayA[4] = ArrayB[4], 'ArrayA[4] <> ArrayB[4]');
end;

这是通过以线性方式布置数组的事实,因此您在第一个数组位置以阵列的长度来复制字节。

您可以强迫编译器通过打字来假设它们是相同类型的:

type
  TIntArray = array[1..4] of integer;

begin
  Assert(SizeOf(ArrayA) = SizeOf(TIntArray));
  Assert(SizeOf(ArrayB) = SizeOf(TIntArray));
  TIntArray(ArrayA) := TIntArray(ArrayB);

但是,您应该确保两者实际上都是数组[1..4],否则您将覆盖一些内存。这就是为什么我添加了两个断言。

Just use UnitA in UnitB after inteface and before the implementation ...!!!!

Never, never, NEVER use code like this:

// This is where the move from ArrayA to ArrayB happens.
Move( ArrayA[1], ArrayB[1], SizeOf(ArrayA) );

Where's the flaw? You're using the SOURCE size to get the number of bytes to move, not the DESTINATION size!!! If SizeOf(A) > SizeOf(B) you have a buffer overflow and you're overwriting memory. If you're luck you get an AV, if you're not you have an exploitable vulnerability. It's far better to always use the destination size, although this way you can end up reading memory you shouldn't if Size(B) > Size(A), maybe exposing unwanted data. Anyway, always check structure boundaries when moving data - some companies banned operations like this (i.e. memcpy() ) from their code.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top