如何在C#中创建自定义属性 [英] How to create a custom attribute in C#

查看:50
本文介绍了如何在C#中创建自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了很多次,但是仍然无法理解自定义属性的用法(我已经遍历了很多链接)。

I have tried lots of times but still I am not able to understand the usage 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?

推荐答案

在代码中创建自定义属性非常简单,了解什么属性非常重要:

While the code to create a custom Attribute is fairly simple, it's very important that you understand what attributes are:

属性是编译到程序中的元数据。属性本身不会为类,属性或模块添加任何功能,而只是添加数据。但是,通过反射,人们可以利用这些属性来创建功能。

Attributes are metadata compiled into your program. Attributes themselves do not add any functionality to a class, property or module - just data. However, using reflection, one can leverage those attributes in order to create functionality.

因此,例如,让我们看一下验证应用程序块,来自Microsoft的企业库。如果您看一个代码示例,将会看到:

So, for instance, let's look at the Validation Application Block, from Microsoft's Enterprise Library. If you look at a 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 the 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; as mentioned previously, it 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 violate 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆