Преобразование ссылки на интерфейс для реализации класса в Delphi 2010 | Participants
|
- Statistics
- Participants
- Translate into Russian
- Translation result
- Translation complete.
If you do not want to register an account, you can sign in with OpenID.
Casting an Interface Reference to the Implementing Class in Delphi 2010 | Преобразование ссылки на интерфейс для реализации класса в Delphi 2010 | |
Not all the new features in Delphi 2010 are big. In fact, the team have spent a lot of time implementing many small features, fixes and tweaks. Some of these may not seem to amount to much individually, but they not only add up to significant impact, but greatly add to the polish of the product. I expect this will be one of those releases that keeps serving up little delights and surprises for a long time. | Не все нововведения в Delphi 2010 большие и заметные. Команда потратила массу времени реализуя множество дополнительных функциональных возможностей, исправлений и улучшений. Некоторые из них могут показаться незначительными по отдельности, но они не только в целом окзывают существенное влияние, но и значительно добавляют гармоничности продукту. | |
One of the features in Delphi 2010 that I expect will spawn much debate is the ability to cast an interface reference back to the type of class that implements it. | Одна из возможностей Delphi 2010, которая, как мне кажется, породит массу споров - это возможность привести интерфейсную ссылку назад к типу класса, реализующего этот интерфейс. | — Одной - несогласованный падеж. — TDelphiBlog |
Let’s say we have an Interface, IMyInterface, and a class that implements that Interface, TMyClass: | Давайте представим, что у нас есть интерфейс IMyInterface и класс TMyClass, который реализует этот интерфейс: | — Наверно показалось IInerface, а тут просто слово интерфейс — r3code — действительно. — TDelphiBlog |
IMyInterface = interface | ||
['{7AD04980-5869-4C93-AC29-C26134511554}'] | ||
procedure Foo; | ||
end; | ||
TMyClass = class(TInterfacedObject, IMyInterface) | ||
procedure Foo; | ||
procedure Bar; | ||
end; | ||
compileerror Further, let’s say we’ve been passed a variable of type IMyInterface. What happens if we want to invoke Bar? Attempting to simply cast the interface reference to a TMyClass would result in a compiler error. | Дальше, давайте представим что нам передали переменную типа IMyInterface. Что случится если мы захотим вызвать Bar? Попытка просто привести интерфейсную ссылку к типу TMyClass приведёт к ошибке компилятора. | |
The most common solution to this I’ve seen is to have a method in the interface that returns the class type, but this kind of defeats much of the value of the interface in the first place, tying the interface to a specific implementation. Further, it’s ugly as a hatful. | Наиболее частое решение, которое я видел, это включить в интерфейс метод, который вернёт тип класса, но оно изничтожает ценность помещения интерфейса на первое место, привязывая интерфейс к конкретной реализации. Более того, оно отвратительно. | — hatful - по ходу отсюда: http://multitran.ru/c/m.exe?a=3&s=hat... — TDelphiBlog кто-нибудь приведите первое предложение в понятный вид. — TDelphiBlog — Первое вроде как привел в вид. — r3code |
Well, such hacks are no longer required. | ||
In Delphi 2010, you can now use the is operator to test to see if an interface type is implemented by a specific class, and if so, cast it to that type and reference any non-interface methods, properties, etc. | В Delphi 2010 вы можете использовать оператор is для того, чтобы проверить реализован ли интерфейс определённым классом, и если это так, привести его к этому классу и использовать неинтерфейсные методы, свойства и т.п. | |
Further, the as operator will throw an EInvalidCast exception if you attempt to cast an interface reference to a class type that it was not actually extracted from. The hard cast will return nil in the same circumstances. (Thanks Allen for the correction!) | Более того, если вы попробуете привести интерфейсную ссылку к типу класса из которого она не была фактически получена, оператор as вызовет исключение EInvalidCast. При тех же условиях жесткое приведение типа вернет nil. | — Блин, че откуда было extracted? — r3code — интерфейсная ссылка была извлечена из класса — TDelphiBlog точнее не была — TDelphiBlog — точно, пропустил НЕ — r3code |
So this code now runs happily: | ||
if MyInterface is TMyClass then | ||
TMyClass(MyInterface).Bar; |

— допереводить — TDelphiBlog
— polish of the product - сглаживание шероховатостей, приведение к идеалу, к гармонии ) Смотрел в словаре синонимов. — r3code