What I am trying to do is to add common methods to these two classes which have the same indirect ancestor.
IMyMethods = interface
procedure SomeMethod;
end;
TMyADODataset =class(TADODataset, IMyMethods) // ADO
public
procedure SomeMethod;
end;
TMyUniDataset =class(TUniTable, IMyMethods) // UniDAC
public
procedure SomeMethod;
end;
SomeMethod
would be implemented differently for ADO and for UniDAC. So I thought an interface is perfect.
Then we have
TMyTable =class
private
FDataset: TDataset;
end;
Here I have choosen TDataset as that is the common ancestor of TADODataset and TUniTable.
FDataset could be instantiated as follows:
if FProvider = prADO then
FDataset := TMyADODataset.Create
else
FDataset := TMyUniDataset.Create;
Now the problem is how to call SomeMethod
of FDataset
, the following does not compile and gives a type incompatibility error:
IMyMethods(FDataset).SomeMethod;
This is because TDataset
does not implement IMyMethods
, which is correct. But is there any way I can trick the compiler into accepting this? Or is there a better solution? I thought of class helpers but the implentation of SomeMethod
will be different for ADO and UniDAC.
CodePudding user response:
Use the SysUtils.Supports()
function to obtain the IMyMethods
interface from the FDataset
object, eg:
uses
..., SysUtils;
var
Intf: IMyMethods;
...
if Supports(FDataset, IMyMethods, Intf) then
Intf.SomeMethod;
Just note that, in order for this to work, IMyMethods
needs to have a Guid assigned to it, eg:
type
IMyMethods = interface
['{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}']
procedure SomeMethod;
end;
You can generate a new Guid directly in the Code Editor by pressing Ctrl Shift G.