Преобразование ссылки на интерфейс для реализации класса в Delphi 2010

Malcolm Groves, “Casting an Interface Reference to the Implementing Class in Delphi 2010”, public translation into Russian from English More about this translation.

See also 15 similar translations

Translate into another language.

Participants

TDelphiBlog173 points
r3code157 points
VesninAndrey11 points
Join Translated.by to translate! If you already have a Translated.by account, please sign in.
If you do not want to register an account, you can sign in with OpenID.
Pages: ← previous Ctrl next next untranslated
1 2

Casting an Interface Reference to the Implementing Class in Delphi 2010

Преобразование ссылки на интерфейс для реализации класса в Delphi 2010

History of edits (Latest: r3code 2 years, 3 months ago) §

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 большие и заметные. Команда потратила массу времени реализуя множество дополнительных функциональных возможностей, исправлений и улучшений. Некоторые из них могут показаться незначительными по отдельности, но они не только в целом окзывают существенное влияние, но и значительно добавляют гармоничности продукту.

History of edits (Latest: r3code 2 years, 3 months ago) §

— допереводить TDelphiBlog

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

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, которая, как мне кажется, породит массу споров - это возможность привести интерфейсную ссылку назад к типу класса, реализующего этот интерфейс.

Unapproved edits (Latest: r3code 2 years, 3 months ago) §

— Одной - несогласованный падеж. TDelphiBlog

Let’s say we have an Interface, IMyInterface, and a class that implements that Interface, TMyClass:

Давайте представим, что у нас есть интерфейс IMyInterface и класс TMyClass, который реализует этот интерфейс:

History of edits (Latest: r3code 2 years, 3 months ago) §

— Наверно показалось IInerface, а тут просто слово интерфейс r3code

— действительно. TDelphiBlog

IMyInterface = interface

IMyInterface = interface

History of edits (Latest: r3code 2 years, 3 months ago) §

['{7AD04980-5869-4C93-AC29-C26134511554}']

['{7AD04980-5869-4C93-AC29-C26134511554}']

History of edits (Latest: r3code 2 years, 3 months ago) §

procedure Foo;

procedure Foo;

History of edits (Latest: r3code 2 years, 3 months ago) §

end;

end;

History of edits (Latest: r3code 2 years, 3 months ago) §

TMyClass = class(TInterfacedObject, IMyInterface)

TMyClass = class(TInterfacedObject, IMyInterface)

History of edits (Latest: r3code 2 years, 3 months ago) §

procedure Foo;

procedure Foo;

History of edits (Latest: r3code 2 years, 3 months ago) §

procedure Bar;

procedure Bar;

History of edits (Latest: r3code 2 years, 3 months ago) §

end;

end;

History of edits (Latest: r3code 2 years, 3 months ago) §

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 приведёт к ошибке компилятора.

History of edits (Latest: TDelphiBlog 2 years, 3 months ago) §

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.

Наиболее частое решение, которое я видел, это включить в интерфейс метод, который вернёт тип класса, но оно изничтожает ценность помещения интерфейса на первое место, привязывая интерфейс к конкретной реализации. Более того, оно отвратительно.

History of edits (Latest: TDelphiBlog 2 years, 3 months ago) §

— hatful - по ходу отсюда: http://multitran.ru/c/m.exe?a=3&s=hat... TDelphiBlog

кто-нибудь приведите первое предложение в понятный вид. TDelphiBlog

— Первое вроде как привел в вид. r3code

Well, such hacks are no longer required.

Что же, такие приёмы теперь не нужны.

History of edits (Latest: r3code 2 years, 3 months ago) §

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 для того, чтобы проверить реализован ли интерфейс определённым классом, и если это так, привести его к этому классу и использовать неинтерфейсные методы, свойства и т.п.

History of edits (Latest: r3code 2 years, 3 months ago) §

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.

History of edits (Latest: TDelphiBlog 2 years, 3 months ago) §

— Блин, че откуда было extracted? r3code

— интерфейсная ссылка была извлечена из класса TDelphiBlog

точнее не была TDelphiBlog

— точно, пропустил НЕ r3code

So this code now runs happily:

Теперь этот код запускается успешно:

History of edits (Latest: VesninAndrey 2 years, 3 months ago) §

if MyInterface is TMyClass then

if MyInterface is TMyClass then

History of edits (Latest: r3code 2 years, 3 months ago) §

TMyClass(MyInterface).Bar;

TMyClass(MyInterface).Bar;

History of edits (Latest: r3code 2 years, 3 months ago) §
Pages: ← previous Ctrl next next untranslated
1 2