Подробнее об атрибутах в 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.
More Attributes in Delphi 2010 | ||
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, я показал основы связанные с созданием, применением и опросом атрибутов. Однако, я не привел пример, для чего вы могли бы их использовать. | |
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). | |
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. | Обратите внимание, то что будет показано ниже, это только пример использования атрибутов, а не полный фреймворк для проверки данных. Рассматривайте его, как испытание концепции, а не как готовый код. | |
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 для обработки любого переданного объекта и проверяющий каждый клик для полноразмерного изображения. Значения свойств соответствуют атрибутам присоединенным к ним. | |
Make sense? OK, let’s have a look. | ||
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. | Я определил несколько атрибутов для проверки данных, чтобы показать как они работают с разными типами. Создана небольшая иерархия, которая делает код проверки чуть более общим. Я создал атрибуты только для строк и чисел, но вы поймете эту идею. | |
If we have a look at the source for one of the leaf classes, the definition looks like this: | ||
MinimumIntegerAttribute = class(BaseIntegerValidationAttribute) | MinimumIntegerAttribute = class(BaseIntegerValidationAttribute) | |
private | ||
FMinimumValue: Integer; | ||
public | ||
constructor Create(MinimumValue : Integer; const FailureMessage : string); | constructor Create(MinimumValue : Integer; const FailureMessage : string); | |
function Validate(Value : Integer) : boolean; override; | ||
end; | ||
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: | Конструктор содержит два параметра, метод проверки очень прост (в этом случае правило простое). Выглядит это так: |
