创建自定义属性在C# [英] creating custom attribute in C#
问题描述
我已经尝试了很多次,但仍然无法理解自定义属性的使用(我已经经历了许多链接)。
I have tried lots of times but still I am not able to understand the use of custom attributes (I have already gone through lots of links).
任何人请给我解释一个有代码的自定义属性的非常基本的例子。
Can anyone please explain to me a very basic example of a custom attribute with code?
推荐答案
=http://msdn.microsoft.com/en-us/library/system.attribute.aspx>属性非常简单,了解属性是非常重要的:
While the code to create a custom Attribute is fairly simple, it's much important that you understand what are attributes:
属性是元数据编译到您的程序。属性本身不向类,属性或模块添加任何功能,只是数据。但是,使用反射,可以利用这些属性来创建功能。
Attributes are metadata compiled into your program. Attributes themselves doesn't add any functionality to a class, property or module, just data. However, using reflection, one can leverage those attributes in order to create functionality.
例如,让我们看看验证应用程序块,来自 Enterprise Library 。如果你看代码示例,你会看到:
So, for instance, let's look at Validation Application Block, from Enterprise Library. If you look at an code example, you'll see:
/// <summary>
/// blah blah code.
/// </summary>
[DataMember]
[StringLengthValidator(8, RangeBoundaryType.Inclusive, 8, RangeBoundaryType.Inclusive, MessageTemplate = "\"{1}\" must always have \"{4}\" characters.")]
public string Code { get; set; }
从上面的代码段中,可能会猜到代码将始终被验证,验证器的规则(在示例中,至少有8个字符,最多8个字符)。但实际上,属性不做任何事情,只是向属性添加元数据。
From the snippet above, one might guess that Code will always be validated, whenever changed, accordingly to the rules of the Validator (in the example, have at least 8 characters and at most 8 characters). But the truth is that the Attribute does nothing, only adds metadata to the property.
但是,企业库有一个 Validation.Validate
方法来查看你的对象,并且对于每个属性,它将检查内容是否违反属性通知的规则。
However, the Enterprise Library has a Validation.Validate
method that will look into your object, and for each property, it'll check if the contents violates the rule informed by the attribute.
所以,这就是你应该如何考虑属性 - 一种方法来添加数据到你的代码,以后可能被其他方法/类等使用。
So, that's how you should think about attributes -- a way to add data to your code that might be later used by other methods/classes/etc.
这篇关于创建自定义属性在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!