Delphi对象转换

Red*_*ift 2 delphi casting

我有一个主类和几个实现具有相同名称的方法的继承类,如下所示:

MainClass = class(TImage)
  //main class methods...
end;

MyClass1 = class(MainClass)
  procedure DoSomething;
end;

MyClass2 = class(MainClass)
  procedure DoSomething;
end;

MyClass3 = class(MainClass)
  procedure DoSomething;
end;
Run Code Online (Sandbox Code Playgroud)

我还有一个TList包含指向对象实例(几个类)的指针.如果我想DoSomething为每个班级调用正确的程序,我是否使用以下内容?

if TList[i] is MyClass1 then
  MyClass1(TList[i]).DoSomething
else if TList[i] is MyClass2 then
  MyClass2(TList[i]).DoSomething
else if TList[i] is MyClass3 then
  MyClass3(TList[i]).DoSomething
Run Code Online (Sandbox Code Playgroud)

是否有一些转换方法允许我在几行代码中执行此操作?

Kor*_*icz 10

是的,虚拟多态:)

MainClass = class(TImage)
  procedure DoSomething; virtual;
end;

MyClass1 = class(MainClass)
  procedure DoSomething; override;
end;

MyClass2 = class(MainClass)
  procedure DoSomething; override;
end;

MyClass3 = class(MainClass)
  procedure DoSomething; override;
end;
Run Code Online (Sandbox Code Playgroud)

然后就是:

if TList[i] is MainClass then
  MainClass(TList[i]).DoSomething
Run Code Online (Sandbox Code Playgroud)

如果您不想执行空MainClass.DoSomething程序,也可以标记它virtual; abstract;.