【发布时间】:2013-03-06 17:18:43
【问题描述】:
我知道的标题很不时髦。
我有一系列文本行,需要按特定顺序执行特定操作。我通过定义以下记录结构想出了一种方法:
TProcessOrderRecord = record
RecordTypes: TByteSet;
InitialiseProcedure: TPreScanProc;
ProcessProcedure: TProcessRecord;
FinaliseProcedure: TEndScanProc;
end;
AProcessOrderArray = array of TProcessOrderRecord;
Initialise 倾向于调用一个构造函数,该构造函数将填充宿主对象中的一个字段。
Process 将是对象上的一个过程,它将为每个与 RecordTypes 中的记录类型匹配的文本行调用。
Finalise 将倾向于调用析构函数,并可能在它知道已处理完整的记录集时进行任何检查。
处理这个数组的方法很简单:
procedure TImport.ScanTransferFile;
var
i: integer;
lArrayToProcess: AProcessOrderArray;
begin
lArrayToProcess := SetUpProcessingOrder(NLPGApp.ImportType);
for i := low(lArrayToProcess) to high(lArrayToProcess) do
begin
ProcessRecordType(lArrayToProcess[i].RecordTypes, lArrayToProcess[i].InitialiseProcedure, lArrayToProcess[i].ProcessProcedure, lArrayToProcess[i].FinaliseProcedure);
end;
end;
procedure TImport.ProcessRecordType(const RecordTypesToFind: TByteSet; PreScanProcedure: TPreScanProc; OnFindRecord: TProcessRecord; OnCompleteScan: TEndScanProc);
var
lLineOfText: string;
lIntegerRecordID: byte;
begin
if Assigned(PreScanProcedure) then PreScanProcedure;
try
if assigned(OnFindRecord) then
begin
Reader.GoToStartOfFile;
while not Reader.EndOfFile do
begin
lLineOfText := Reader.ReadLine;
lIntegerRecordID := StrToIntDef(GetRecordID(lLineOfText), 0);
if lIntegerRecordID in RecordTypesToFind then
begin
try
OnFindRecord(lLineOfText);
except
on E: MyAppException do
begin
// either raise to exit or log and carry on
end;
end;
end;
end;
end;
finally
// OnCompleteScan usually contains calls to destructors, so ensure it's called
if Assigned(OnCompleteScan) then OnCompleteScan;
end;
end;
我的问题是我想这样定义一个记录:
RecordTypes = [10]
InitialiseProcedure = ProcToCreateFMyObj
ProcessProcedure = FMyObj.do
FinaliseProcedure = ProcToFreeFMyObj
这编译得很好,但是当调用 ProcessProcedure 时,因为在设置 ProcessProcedure 时 FMyObj 为 nil,即使现在设置了 FMyObj,TMyObj 的实例也是 nil。有没有什么干净的方法可以让记录在调用时而不是在第一次分配时指向 FMyObj 的实例?
目前我已经在宿主对象上使用“调用者”方法,然后可以在需要时调用 FMyObj 实例,但这会创建一个包含大量单行方法的非常臃肿的对象。
编辑以澄清/复杂化问题
有时FObj 的一个实例可以处理多种类型的记录(通常如果它们具有主从关系)。在这种情况下,第一个记录类型的InitialiseProcedure将创建FObj,第二个记录的FinaliseProcedure将释放FObj,并且每个记录的ProcessProcedure可以引用FObj的不同过程(do1和@ 987654332@).
【问题讨论】:
-
FMyObj 在哪里声明?
-
FMyObj 是 TImport 类的成员。 TImport在设置的时候就存在(所以FMyObj当时是一个有效的指针,只是指向nil)。
-
如果
FMyObj在TImport类中,而ProcessRecordType是同一个类的方法,我不明白为什么需要使用方法指针,因为你可以随时直接调用 FMyObj.Do。你想完成什么? -
我的 AProcessOrderArray 可能包含几组方法,每组方法都使用自己的(或共享)对象。我可以使用大量的 CASE 语句来做到这一点,但是由于我有可能对 AProcessOrderArrays 进行多种配置,因此我更喜欢单独设置它并具有非常简单的调用过程的想法。我真的很想将它们声明为 const 数组,但这会造成更大的悲痛!
-
一定要使用记录,还是可以改成使用类或接口?
标签: delphi delphi-2006