1

I'm doing an event manager in Freepascal
Each event is an object type TEvent (=object), each kind of event must derive from this class.
Events are differentiated by an integer identificator, assigned dynamically.
The problem is that i want to retrieve the event id of an instance, and i can't do it well.

  • All instances of a class(object) have a unique id => so it should be static field.
  • All classes have a diferent id => so it should be virtual.
  • Event ids are assignated in run time, and can change => so it can't be a simple method

In sum, I can't put all this together.
I'm looking for an elegant solution, i don't want to write a hardcoded table, actualizing it in every constructor... etc, i'd prefer something taking advantage of the polymorphism
Can anyone help me with another technical or design solution?
I remark I don't want to use class instead of object construct.(property doesn't work on objects? :(

4

2 回答 2

0

您可以像这样制作一个简单的表格/列表:

unit classids;

{$mode objfpc}{$H+}

interface

function GetClassID(c:TClass):Integer;
procedure SetClassID(c:TClass; id:Integer);

property ClassID[c:TClass]:Integer read GetClassID write SetClassID;

implementation
uses Maps;

var Map:TMap;

function GetClassID(c:TClass):Integer;
begin
 if not Map.GetData(c,Result) then
  Result:=0; //Or any default you like
end;

procedure SetClassID(c:TClass; id:Integer);
begin
 Map.Delete(c);
 Map.Add(c,id);
end;

initialization
 Map:=TMap.Create(itu4,SizeOf(Integer));
finalization
 FreeAndNil(Map);
end.

然后你可以获取/设置ID

ClassID[TMyObject]:=12;
ShowMessage(IntToStr(ClassID[TMyObject])); //shows 12

祝你好运

于 2011-10-23T02:49:24.543 回答
0

您可能需要类 var 之类的东西,例如在较新的 delphi 中。但这仅在 FPC 的开发版本中(2.5.1+)。

请注意,对象类型是 TP 遗留的,并且在这个千年中没有被开发出来,我不希望这会改变。如果你需要的比它提供的更多,我建议使用类。

于 2010-04-10T22:29:23.073 回答