开发者

What does .Add mean when used in a constructor?

I come from a vb/c# background and I am having difficulty understanding the meaning of part of the following code, specifically the bit 'self.fColConsignments.Add'

TConsignment = class(TCollectionItem)
constructor Create(Collection : TCollection); override;

...

function TIFCSUMMsg.AddConsignment: TConsignment;
begin
  result := TConsignment(self.fColConsignments.Add);
开发者_如何学Cend;


if you background is C#, don't missinterpret that line:

result := TConsignment(self.fColConsignments.Add);

it's just a type cast and not a constructor call. In C# it would look like:

result = (TConsignment)self.fColConsignments.Add;


Presumably fcolConsignments is a collection owned by the TIFCSUMMsg instance (Self). Add adds a new item to the collection and returns the reference as the result. The result is then cast to a TConsignment to fit the result type of the AddConsignment method.


self.fColConsignments.Add probably adds a new item into fColConsignments, which must be a collection or similar, and returns it. But the declared return type may be more generic than the actual object returned, then a typecast is applied by using TConsignment(object).


The code in your example IS NOT A CONSTRUCTOR.

In C++/C#/Java/(put your C descendant language here), constructors are nameless methods. So:

class TFoo {
TFoo() { // do something }
}

....
{
   TFoo myFoo;
   myFoo = new TFoo()
    .....
}

This a typical construction on such languages. This is NOT how Delphi works.
Constructors in Delphi have names. The convention is that they are called .Create and
they can be static or virtual ones (like any method).

The code above can be converted to:

TFoo = class 
  constructor Create();
end;
...
constructor TFoo.Create()
begin
  // Do something;
end;

....
// Creating an object
var
  myFoo: TFoo;
begin
  myFoo := TFoo.Create();  
  ...
end;

The code you exemplified were not an constructor but a
kind of typecast. You can get more information about this (typecasts and constructors)
in the Delphi Language Guide (or Object Pascal Language Guide, depending
on the Delphi version you have available).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜