我知道 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?
谢谢
来自 Pro C# 2008 和 .NET 3.5 平台,Andrew Troelsen 的第四版
.NET 编译器的一个作用是生成元数据所有定义和引用类型的描述.除了这个标准的元数据包含在任何程序集中,.NET 平台为程序员提供了一种嵌入附加使用属性将元数据放入程序集中.简而言之,属性只不过是代码可以应用于给定类型(类、接口、结构等)、成员(属性、方法等)、程序集或模块.使用属性注释代码的想法并不新鲜.COM IDL 提供了许多预定义的允许开发人员描述给定 COM 服务器中包含的类型的属性.然而,COM 属性只不过是一组关键字.如果 COM 开发人员需要创建一个自定义属性,他或她可以这样做,但它在代码中被一个 128 位数字引用(GUID),这充其量是麻烦的.与 COM IDL 属性(同样只是关键字)不同,.NET 属性是类类型扩展抽象 System.Attribute 基类.在探索 .NET 命名空间时,您将找到许多可以在应用程序中使用的预定义属性.此外,您可以自由构建自定义属性,通过创建一个从属性派生的新类型.了解当您在代码中应用属性时,嵌入的元数据本质上是直到另一个软件明确地反映了这些信息之前,它是无用的.如果不是这种情况,嵌入在程序集中的元数据简介被忽略且完全无害.
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) 本身已被预编程为在编译周期中发现各种属性的存在.例如,如果 C#编译器遇到[CLSCompliant]属性,会自动检查属性项到确保它只公开符合 CLS 的构造.再举一个例子,如果 C# 编译器发现具有 [Obsolete] 属性的项目,它将在Visual Studio 2008 错误列表窗口.除了开发工具之外,.NET 基类库中的许多方法都是预编程的反映特定的属性.例如,如果您希望保持对象到文件,您需要做的就是使用 [Serializable] 属性注释您的类.如果BinaryFormatter类的Serialize()方法遇到这个属性,对象自动以紧凑的二进制格式保存到文件中..NET CLR 也在寻找某些属性的存在.也许是最著名的 .NET 属性是 [WebMethod].如果您希望通过 HTTP 请求并自动公开方法将方法返回值编码为 XML,只需将 [WebMethod] 应用于方法和CLR 处理细节.除了 Web 服务开发之外,属性对于.NET 安全系统、Windows Communication Foundation 和 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 基类库提供了许多不同的属性命名空间.下面是一些(但绝不是全部)预定义的快照属性.
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 代码调用任何基于非托管 C 或 C++ 的代码库,包括底层操作系统的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.
标记不推荐使用的类型或成员.如果其他程序员尝试使用这样一个项目,他们将收到一个编译器警告,描述错误他们的方式.
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 提供了一个名为 Attribute 的代码片段,它将转储出一个新的 System.将属性派生类添加到您的代码窗口中.
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# 中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!