Why does the first statement compile but not the second?

时间:2016-04-04 16:54:30

标签: delphi

See code below. It is an AfterOpen event of a ClientDataSet.
Why does the second statement NOT compile?
The error message is: Undeclared identifier: 'LogChanges'
The third statement compiles.
Is the third statement correct, and equivalent to the first one?
If 'DataSet' cannot be used, why is it passed?

procedure TCTL_Configurator_form.cdsZonesAfterOpen(DataSet: TDataSet);
begin
  cdsZones.LogChanges                 := FALSE; // This line compiles
  DataSet.LogChanges                  := FALSE; // This line does NOT compile
  TClientDataSet(DataSet).LogChanges  := FALSE; // This line compiles
end;

1 个答案:

答案 0 :(得分:5)

TDataSet没有方法LogChanges。它是在TClientDataSet中引入的,这就是第三行编译的原因;您将DataSet转换为更具体的TClientDataSet。正如Anthony在评论中指出的那样,如果DataSet实际上不是TClientDataSet或TClientDataSet的后代,则类型转换会在运行时导致访问冲突 - 更好的选择是使用(DataSet as TClientDataSet)进行检查,或者使用if DataSet is TClientDataSet

AfterOpen中引入了TDataSet事件,它会收到一个普通的TDataSet作为参数。