Кратко о RTTI и атрибутах в Delphi 2010

Malcolm Groves, “RTTI and Attributes in Delphi 2010”, public translation into Russian from English More about this translation.

See also 13 similar translations

Translate into another language.

Participants

r3code458 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

RTTI and Attributes in Delphi 2010

Кратко о RTTI и атрибутах в Delphi 2010

History of edits (Latest: r3code 1 year, 11 months ago) §

RTTI (Runtime Type Information) has had a major overhaul in Delphi 2010. RTTI is a central piece on which the Delphi IDE is written, and as such has been around since the first release, however I’ve heard from a number of people over the years that they’d tried to use RTTI and found it too difficult and arcane, especially compared to the Reflection API’s in Java and .NET. That’s a real shame, as the ability to write code to query the details of other objects, without knowing the type up-front, is really powerful.

RTTI (Runtime Type Information) было тщательно переработано в Delphi 2010. RTTI является центральным элементом, на котором написано Delphi IDE, он существует со времен первого выпуска, однако я слышал от некоторых людей на протяжении многих лет, что они попытались использовать RTTI и нашли это слишком сложным и замысловатым, особенно по сравнению с Reflection API в Java и. NET. Вот это настоящий позор, поскольку возможность писать код для запроса подробной информации о других объектах, не зная заранее их типа, это действительно мощная возможность.

History of edits (Latest: r3code 1 year, 11 months ago) §

However, I think that complaint will be a thing of the past with this new API. It’s been not only extended to make it more capable, it is also now much more approachable and easy to use.

Однако, я думаю, что жалобы уйдут в прошлое с новым API. Оно было не только расширено, но стало гораздо более доступным и легким в использовании.

History of edits (Latest: r3code 1 year, 11 months ago) §

One of the new features that I’m very excited about is support for Attributes in Win32. I’m working on a larger example, but here’s a quick run through of creating and then querying custom attributes.

Одна из новых особенностей, которой я очень впечатлен - это поддержка атрибутов в среде Win32. Я работаю над большим примером, но здесь мы быстренько рассмотрим создание, а затем запрос пользовательских атрибутов.

History of edits (Latest: r3code 1 year, 11 months ago) §

Custom attributes are simply classes that descend from TCustomAttribute. They can have properties, methods, etc, like any other class:

Пользовательские атрибуты это просто классы, которые наследованы от TCustomAttribute. Они могут иметь свойства, методы и т.д., как и любой другой класс:

History of edits (Latest: r3code 1 year, 11 months ago) §

MyAttribute = class(TCustomAttribute)

MyAttribute = class(TCustomAttribute)

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

private

private

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

FName: string;

FName: string;

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

FAge: Integer;

FAge: Integer;

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

public

public

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

constructor Create(const Name : string; Age : Integer);

constructor Create(const Name : string; Age : Integer);

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

property Name : string read FName write FName;

property Name : string read FName write FName;

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

property Age : Integer read FAge write FAge;

property Age : Integer read FAge write FAge;

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

end;

end;

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

No real surprises here, and the constructor is implemented exactly as you’d expect.

Здесь никаких неожиданностей, конструктор описан именно так как ты этого ожидал.

History of edits (Latest: r3code 1 year, 11 months ago) §

Next, we can apply our attribute to our class:

Далее мы можем применить наш атрибут к классу:

History of edits (Latest: r3code 1 year, 11 months ago) §

TMyClass = class

TMyClass = class

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

public

public

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

[MyAttribute('Malcolm', 39)]

[MyAttribute('Malcolm', 39)]

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

procedure MyProc(const s : string);

procedure MyProc(const s : string);

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

[MyAttribute('Julie', 37)]

[MyAttribute('Julie', 37)]

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

procedure MyOtherProc;

procedure MyOtherProc;

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

end;

end;

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

Here I’ve applied it to both methods, but note I’ve supplied different parameters to the Attribute. Also note the order of the parameters matches the order in the constructor. This is not just limited to methods, you can apply attributes to properties, entire classes, all sorts of things.

Здесь я применяю атрибут к обоим методам, но задаю разные параметры атрибуту. Порядок записи параметров соответствует их порядку в конструкторе. Применение атрибутов не ограниченно одними методами, вы можете применять атрибуты в свойствам, классам, к любым другим сущностям.

History of edits (Latest: r3code 1 year, 11 months ago) §

Of course, there’s no point adding attributes if you can’t read them from somewhere, so here’s some sample code that uses the new RTTI API to query for our attributes, and display the details in a listbox:

Конечно, нет смысла добавлять атрибуты, если вы не можете прочитать их откуда-нибудь, так что вот некоторые примеры кода, который использует новый API RTTI для запроса наших атрибутов, а также отображения деталей в ListBox:

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