📜 ⬆️ ⬇️

Convert an interface reference to implement a class in Delphi 2010

Not all innovations in Delphi 2010 are big and noticeable. The team spent a lot of time implementing a lot of additional functionality, fixes and improvements. Some of them may seem insignificant separately, but they not only generally have a significant impact, but also significantly add harmony to the product.

One of the features of Delphi 2010, which, I think, will create a lot of controversy is the ability to bring the interface link back to the type of class that implements this interface.

Let's imagine that we have an IMyInterface interface and a TMyClass class that implements this interface:

IMyInterface = interface
[ '{7AD04980-5869-4C93-AC29-C26134511554}' ]
procedure Foo;
end;

TMyClass = class (TInterfacedObject, IMyInterface)
procedure Foo;
procedure Bar;
end;


Next, let's imagine that we were given a variable of type IMyInterface . What happens if we want to call Bar ? Attempting to simply cast the interface reference to the TMyClass type will result in a compiler error.
')
The most common solution I've seen is to include in the interface a method that returns the class type, but it destroys the value of putting the interface in the first place, binding the interface to a specific implementation. Moreover, it is disgusting.

Such techniques are no longer needed.

In Delphi 2010, you can use the is operator to check whether the interface is implemented by a particular class, and if so, bring it to this class and use non-interface methods, properties, etc.

Moreover, if you try to cast the interface reference to a class type from which it was not actually obtained, the as operator will throw an EInvalidCast exception. Under the same conditions, a hard type conversion will return nil .

Now this code runs successfully:
if MyInterface is TMyClass then
TMyClass(MyInterface).Bar;


Of course, this should be used with understanding. For example, the usual compiler warnings about saving the interface with reference counting and object references without counting the references to the same instance remain valid.



You can help improve the translation.
translated.by/you/casting-an-interface-reference-to-the-implementing-class-in-delphi-2010/into-ru
Translators: r3code , debose , VesninAndrey

Source: https://habr.com/ru/post/85504/


All Articles