属性在C# [英] Attributes in C#

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

问题描述

我知道C#(和.NET一般)大的属性。然而,尽管我已经在C#编程多年的事实,我还没有发现自己曾经使用它们。会有人让我开始对他们,并解释在这里是最好的使用他们?

I know that C# (and .NET in general) is big on attributes. However, despite the fact I have programmed in C# for many years, I haven't found myself ever using them. Would someone get me started on them, and explain where is the best to use them?

感谢

推荐答案

临C#2008和.NET 3.5平台,第四版由Andrew Troelsen

一个.NET编译器的一个作用是生成的元数据 描述所有的定义和引用类型。除了这个标准元数据包含 任何组件内,.NET平台提供了一种手段,程序员嵌入其他 元数据将使用属性的组件。简而言之,属性比code仅此而已 可以施加到给定类型(类,接口,结构等),构件(属性注释, 法等),组件,或模块。 使用属性注释code的想法并不新鲜。 COM IDL提供了许多predefined 属性,允许开发人员描述包含一个给定的COM服务器中的类型。 但是,COM属性比一组关键字更小。如果一个COM开发商需要 创建一个自定义属性,他或她可以这样做,但它是在code引用的一个128位的数字 (GUID),​​这充其量是繁琐。 不同于COM IDL属性(而这又是简单的关键字),.NET属性类类型 该扩展抽象System.Attribute基类。当你探索.NET命名空间,你会 发现许多predefined属性,你能够使用你的应用程序。此外, 你可以自由创建一个构建定制属性,以进一步验证你的类型的行为 新型的从属性派生。 要知道,当你申请你的code的属性,嵌入式元数据本质上是 没用到另一个软件明确地反映了信息。如果不是这种情况, 元数据嵌入组件内的导语被忽略,完全无害。

One role of a .NET compiler is to generate metadata descriptions for all defined and referenced types. In addition to this standard metadata contained within any assembly, the .NET platform provides a way for programmers to embed additional metadata into an assembly using attributes. In a nutshell, attributes are nothing more than code annotations that can be applied to a given type (class, interface, structure, etc.), member (property, method, etc.), assembly, or module. The idea of annotating code using attributes is not new. COM IDL provided numerous predefined attributes that allowed developers to describe the types contained within a given COM server. However, COM attributes were little more than a set of keywords. If a COM developer needed to create a custom attribute, he or she could do so, but it was referenced in code by a 128-bit number (GUID), which was cumbersome at best. Unlike COM IDL attributes (which again were simply keywords), .NET attributes are class types that extend the abstract System.Attribute base class. As you explore the .NET namespaces, you will find many predefined attributes that you are able to make use of in your applications. Furthermore, you are free to build custom attributes to further qualify the behavior of your types by creating a new type deriving from Attribute. Understand that when you apply attributes in your code, the embedded metadata is essentially useless until another piece of software explicitly reflects over the information. If this is not the case, the blurb of metadata embedded within the assembly is ignored and completely harmless.

正如您所猜测的,.NET 3.5 Framework SDK中附带了大量的实用程序,确实是在 望风的各种属性。 C#编译器(Csc.exe)本身已经pprogrammed至$ P $ 在编译周期中发现的各种属性的presence。例如,如果C# 编译器遇到[CLSCompliant]属性,它会自动检查归结项目 确保其只露出符合CLS的结构。通过另一个示例的方式,如果C#编译 发现由于使用[已过时]属性的物品,它会显示在一个编译器警告 Visual Studio 2008的错误列表窗口。 除了开发工具,在.NET基础类库众多的方法preprogrammed 反映了特定的属性。例如,如果你想坚持的状态 反对文件,你需要做的是用[Serializable]属性注释你的类。如果 BinaryFormatter类的序列化()方法遇到这个属性,对象是自动 坚持在一个紧凑的二进制格式文件。 在.NET CLR也伺机对某些属性的presence。或许最 著名的.NET属性[WebMethod的。如果您想通过HTTP请求和自动曝光的方法 EN code方法的返回值作为XML,简单地套用[WebMethod的]的方法和 CLR处理的细节。除了Web服务开发,属性是操作关键 在.NET安全系统,Windows通讯基础,和COM / .NET互操作性 (等等)。 最后,您可以自由构建编程反映过来自己的自定义应用程序 属性以及在.NET基类库任何属性。通过这样做,你基本上是 能够创建一组由一组特定组件的理解关键词的

As you would guess, the .NET 3.5 Framework SDK ships with numerous utilities that are indeed on the lookout for various attributes. The C# compiler (csc.exe) itself has been preprogrammed to discover the presence of various attributes during the compilation cycle. For example, if the C# compiler encounters the [CLSCompliant] attribute, it will automatically check the attributed item to ensure it is exposing only CLS-compliant constructs. By way of another example, if the C# compiler discovers an item attributed with the [Obsolete] attribute, it will display a compiler warning in the Visual Studio 2008 Error List window. In addition to development tools, numerous methods in the .NET base class libraries are preprogrammed to reflect over specific attributes. For example, if you wish to persist the state of an object to file, all you are required to do is annotate your class with the [Serializable] attribute. If the Serialize() method of the BinaryFormatter class encounters this attribute, the object is automatically persisted to file in a compact binary format. The .NET CLR is also on the prowl for the presence of certain attributes. Perhaps the most famous .NET attribute is [WebMethod]. If you wish to expose a method via HTTP requests and automatically encode the method return value as XML, simply apply [WebMethod] to the method and the CLR handles the details. Beyond web service development, attributes are critical to the operation of the .NET security system, Windows Communication Foundation, and COM/.NET interoperability (and so on). Finally, you are free to build applications that are programmed to reflect over your own custom attributes as well as any attribute in the .NET base class libraries. By doing so, you are essentially able to create a set of "keywords" that are understood by a specific set of assemblies.

在.NET基础类库提供了大量的各种属性 命名空间。下面是一个快照一些,但绝对没有意思清一色predefined 属性。

The .NET base class library provides a number of attributes in various namespaces. Below is a snapshot of some—but by absolutely no means all—predefined attributes.

强制执行的注释项目以符合共同的规则 语言规范(CLS)。回想一下,符合CLS的类型 保证无缝地使用在所有的.NET编程语言。

Enforces the annotated item to conform to the rules of the Common Language Specification (CLS). Recall that CLS-compliant types are guaranteed to be used seamlessly across all .NET programming languages.

允许.NET code来调用任何非托管的C或C ++ - 基于code 库,包括底层操作系统的API。请注意, 与基于COM的软件进行通信时[的DllImport]不被使用。

Allows .NET code to make calls to any unmanaged C- or C++-based code library, including the API of the underlying operating system. Do note that [DllImport] is not used when communicating with COM-based software.

标记的去precated类型或成员。如果其他程序员尝试使用 这样一个项目,他们将收到描述错误编译器警告 他们的道路。

Marks a deprecated type or member. If other programmers attempt to use such an item, they will receive a compiler warning describing the error of their ways.

标记一个类或结构为序列化,这意味着它能够持续 其当前状态到流。

Marks a class or structure as being "serializable," meaning it is able to persist its current state into a stream.

指定在一类或结构的给定字段不应被持久 在序列化过程。

Specifies that a given field in a class or structure should not be persisted during the serialization process.

标记的方法,通过HTTP请求是可调用,并指示CLR 序列化方法的返回值的XML。

Marks a method as being invokable via HTTP requests and instructs the CLR to serialize the method return value as XML.

在构建自定义属性的第一步是创建一个从System.Attribute一个新的类继承。例如:

The first step in building a custom attribute is to create a new class deriving from System.Attribute. Example:

// A custom attribute.
public sealed class VehicleDescriptionAttribute : System.Attribute
{
    private string msgData;

    public VehicleDescriptionAttribute(string description)
    {
        msgData = description;
    }

    public VehicleDescriptionAttribute() { }

    public string Description
    {
        get { return msgData; }
        set { msgData = value; }
    }
}

正如你所看到的,VehicleDescriptionAttribute有一个专用的内部字符串(MSGDATA) 可以使用自定义的构造来设置和使用类型属性(描述)操纵。 除此之外,这个类从System.Attribute派生的事实,没有什么独特的这一类 定义。

As you can see, VehicleDescriptionAttribute maintains a private internal string (msgData) that can be set using a custom constructor and manipulated using a type property (Description). Beyond the fact that this class derived from System.Attribute, there is nothing unique to this class definition.

有关安全方面的原因,它被认为是设计所有自定义一个.NET最佳实践的属性密封。在 事实上,Visual Studio 2008中提供了一个code段命名属性,将转储出一个新的系统。 属性的派生类到code窗口。

For security reasons, it is considered a .NET best practice to design all custom attributes as sealed. In fact, Visual Studio 2008 provides a code snippet named Attribute that will dump out a new System. Attribute-derived class into your code window.

这篇关于属性在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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