Подробнее об атрибутах в Delphi 2010

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

See also 12 similar translations

Translate into another language.

Participants

r3code834 points
TDelphiBlog2 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 3

More Attributes in Delphi 2010

Подробнее об атрибутах в Delphi 2010

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

In my previous post on Attributes in Delphi 2010, I showed a basic view of the mechanics involved in creating, applying and querying Attributes. I didn’t really cover an example of why you might use them.

В моей предыдущей статье Кратко об атрибутах в Delphi 2010, я показал основы связанные с созданием, применением и опросом атрибутов. Однако, я не привел пример, для чего вы могли бы их использовать.

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

Probably the most common example given is for persistence, and indeed, someone over on the Wings of Wind website has posted an example along those lines. I’d like to show off a different use for them: Validation.

Вероятно, наиболее распространенным является пример для персистентности, и, действительно, кто-то опубликовал подобный пример на сайте Wings of Wind. Я хотел бы показать другое их применение - для проверки данных (Validation).

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

Note, what I’ll show you below is meant to be an example of attribute usage, not an example of a robust, complete validation framework. View it like a proof of concept, not finished code.

Обратите внимание, то что будет показано ниже, это только пример использования атрибутов, а не полный фреймворк для проверки данных. Рассматривайте его, как испытание концепции, а не как готовый код.

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

OK, disclaimers out of the way, in this scenario I’d like to be able to add meta-data to my classes specifying validation rules. Maybe I want to be able to say that for my TPerson class to be considered valid, it must have a non-empty Name value, and the Age value must be between 18 to 65. One way to achieve this is to decorate the relevant properties with Attributes specifying these rules, and then have some code that uses RTTI to walk through whatever object is passed to it and validates each of Click for full size image.the property values according to the attributes attached to it.

Итак, с предупреждениями закончили, в таком случае я бы хотел иметь возможность добавить в мои классы метаданные указывающие правила проверки. Может быть, я хочу чтобы класс TPerson класс считался верным, когда Name - это непустое значение и значение Age лежит в диапазоне от 18 до 65. Один из способов добиться этого снабдить соответствующие свойства атрибутами, определяющими эти правила, и затем задействовать некоторый код, использующий RTTI для обработки любого переданного объекта и проверяющий каждый клик для полноразмерного изображения. Значения свойств соответствуют атрибутам присоединенным к ним.

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

Make sense? OK, let’s have a look.

Уловили? Отлично, теперь давайте посмотрим.

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

I’ve defined a few Validation attributes. Not a full set, just a few to show them working on different types. There’s a small hierarchy which makes the validation code a little more generic. So far I’ve only created Attributes for strings and Integers, but you should get the idea.

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

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

If we have a look at the source for one of the leaf classes, the definition looks like this:

Взглянем на исходный код на одного из классов:

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

MinimumIntegerAttribute = class(BaseIntegerValidationAttribute)

MinimumIntegerAttribute = class(BaseIntegerValidationAttribute)

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

private

private

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

FMinimumValue: Integer;

FMinimumValue: Integer;

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

public

public

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

constructor Create(MinimumValue : Integer; const FailureMessage : string);

constructor Create(MinimumValue : Integer; const FailureMessage : string);

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

function Validate(Value : Integer) : boolean; override;

function Validate(Value : Integer) : boolean; override;

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

end;

end;

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

The constructor just stores the two parameters, and the validate method is very simple (well, the rule is simple in this case). It looks like this:

Конструктор содержит два параметра, метод проверки очень прост (в этом случае правило простое). Выглядит это так:

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