Кратко о RTTI и атрибутах в 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.
RTTI and Attributes in Delphi 2010 | ||
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. Вот это настоящий позор, поскольку возможность писать код для запроса подробной информации о других объектах, не зная заранее их типа, это действительно мощная возможность. | |
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. Оно было не только расширено, но стало гораздо более доступным и легким в использовании. | |
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. Я работаю над большим примером, но здесь мы быстренько рассмотрим создание, а затем запрос пользовательских атрибутов. | |
Custom attributes are simply classes that descend from TCustomAttribute. They can have properties, methods, etc, like any other class: | Пользовательские атрибуты это просто классы, которые наследованы от TCustomAttribute. Они могут иметь свойства, методы и т.д., как и любой другой класс: | |
MyAttribute = class(TCustomAttribute) | ||
private | ||
FName: string; | ||
FAge: Integer; | ||
public | ||
constructor Create(const Name : string; Age : Integer); | ||
property Name : string read FName write FName; | ||
property Age : Integer read FAge write FAge; | ||
end; | ||
No real surprises here, and the constructor is implemented exactly as you’d expect. | Здесь никаких неожиданностей, конструктор описан именно так как ты этого ожидал. | |
Next, we can apply our attribute to our class: | ||
TMyClass = class | ||
public | ||
[MyAttribute('Malcolm', 39)] | ||
procedure MyProc(const s : string); | ||
[MyAttribute('Julie', 37)] | ||
procedure MyOtherProc; | ||
end; | ||
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. | Здесь я применяю атрибут к обоим методам, но задаю разные параметры атрибуту. Порядок записи параметров соответствует их порядку в конструкторе. Применение атрибутов не ограниченно одними методами, вы можете применять атрибуты в свойствам, классам, к любым другим сущностям. | |
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: |
