C# attribute(特性)

Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection. For more information, see Reflection (C#).
Attributes have the following properties:
Attributes add metadata to your program. Metadata is information about the types defined in a program. All .NET assemblies contain a specified set of metadata that describes the types and type members defined in the assembly. You can add custom attributes to specify any additional information that is required. For more information, see, Creating Custom Attributes (C#).
You can apply one or more attributes to entire assemblies, modules, or smaller program elements such as classes and properties.
Attributes can accept arguments in the same way as methods and properties.
Your program can examine its own metadata or the metadata in other programs by using reflection. For more information, see Accessing Attributes by Using Reflection (C#).
Using Attributes
Attributes can be placed on most any declaration, though a specific attribute might restrict the types of declarations on which it is valid. In C#, you specify an attribute by placing the name of the attribute, enclosed in square brackets ([]), above the declaration of the entity to which it applies.
In this example, the SerializableAttribute attribute is used to apply a specific characteristic to a class:
C#
[System.Serializable]
public class SampleClass
{
// Objects of this type can be serialized.
}
A method with the attribute DllImportAttribute is declared like this:
C#
using System.Runtime.InteropServices;
C#
[System.Runtime.InteropServices.DllImport(“user32.dll”)]
extern static void SampleMethod();
More than one attribute can be placed on a declaration:
C#
using System.Runtime.InteropServices;
C#
void MethodA([In][Out] ref double x) { }
void MethodB([Out][In] ref double x) { }
void MethodC([In, Out] ref double x) { }
Some attributes can be specified more than once for a given entity. An example of such a multiuse attribute is ConditionalAttribute:
C#
[Conditional(“DEBUG”), Conditional(“TEST1”)]
void TraceMethod()
{
// …
}
System_CAPS_noteNote
By convention, all attribute names end with the word “Attribute” to distinguish them from other items in the .NET Framework. However, you do not need to specify the attribute suffix when using attributes in code. For example, [DllImport] is equivalent to [DllImportAttribute], but DllImportAttribute is the attribute’s actual name in the .NET Framework.
Attribute Parameters
Many attributes have parameters, which can be positional, unnamed, or named. Any positional parameters must be specified in a certain order and cannot be omitted; named parameters are optional and can be specified in any order. Positional parameters are specified first. For example, these three attributes are equivalent:
C#
[DllImport(“user32.dll”)]
[DllImport(“user32.dll”, SetLastError=false, ExactSpelling=false)]
[DllImport(“user32.dll”, ExactSpelling=false, SetLastError=false)]
The first parameter, the DLL name, is positional and always comes first; the others are named. In this case, both named parameters default to false, so they can be omitted. Refer to the individual attribute’s documentation for information on default parameter values.
Attribute Targets
The target of an attribute is the entity to which the attribute applies. For example, an attribute may apply to a class, a particular method, or an entire assembly. By default, an attribute applies to the element that it precedes. But you can also explicitly identify, for example, whether an attribute is applied to a method, or to its parameter, or to its return value.
To explicitly identify an attribute target, use the following syntax:
C#
[target : attribute-list]
The list of possible target values is shown in the following table.
Target value
Applies to
assembly
Entire assembly
module
Current assembly module
field
Field in a class or a struct
event
Event
method
Method or get and set property accessors
param
Method parameters or set property accessor parameters
property
Property
return
Return value of a method, property indexer, or get property accessor
type
Struct, class, interface, enum, or delegate
The following example shows how to apply attributes to assemblies and modules. For more information, see Common Attributes (C#).
C#
using System;
using System.Reflection;
[assembly: AssemblyTitleAttribute(“Production assembly 4”)]
[module: CLSCompliant(true)]
The following example shows how to apply attributes to methods, method parameters, and method return values in C#.
C#
// default: applies to method
[SomeAttr]
int Method1() { return 0; }

// applies to method
[method: SomeAttr]
int Method2() { return 0; }

// applies to return value
[return: SomeAttr]
int Method3() { return 0; }
System_CAPS_noteNote
Regardless of the targets on which SomeAttr is defined to be valid, the return target has to be specified, even if SomeAttr were defined to apply only to return values. In other words, the compiler will not use AttributeUsage information to resolve ambiguous attribute targets. For more information, see AttributeUsage (C#).
Common Uses for Attributes
The following list includes a few of the common uses of attributes in code:
Marking methods using the WebMethod attribute in Web services to indicate that the method should be callable over the SOAP protocol. For more information, see WebMethodAttribute.
Describing how to marshal method parameters when interoperating with native code. For more information, see MarshalAsAttribute.
Describing the COM properties for classes, methods, and interfaces.
Calling unmanaged code using the DllImportAttribute class.
Describing your assembly in terms of title, version, description, or trademark.
Describing which members of a class to serialize for persistence.
Describing how to map between class members and XML nodes for XML serialization.
Describing the security requirements for methods.
Specifying characteristics used to enforce security.
Controlling optimizations by the just-in-time (JIT) compiler so the code remains easy to debug.
Obtaining information about the caller to a method.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Attribute特性是一种用于给程序元素添加额外信息的机制。在C#中,Attribute特性通常以Attribute后缀命名,并且可以附加到类、方法、属性等各种程序元素上。当Attribute特性被应用到程序元素上时,它们可以被用来提供元数据,以帮助编译器、运行时或其他代码分析工具进行处理。 引用中提到了一个约定:自定义的特性名称应该以Attribute后缀结尾。这是因为在将Attribute特性应用到程序元素上时,编译器首先会查找使用的Attribute的定义,如果找不到,则会尝试查找以"Attribute"结尾的同名特性的定义。 在引用中,提到了Attribute特性在ASP.NET开发中的应用。这表明Attribute特性在ASP.NET开发中是非常常见的,并且被广泛使用。 举个例子,引用给出了一个自定义的Attribute特性的示例代码。在这个示例中,定义了一个名为CustomAttribute特性类,它具有一个属性Desc,并提供了两个构造函数。这个示例展示了如何创建自定义的Attribute特性,并将其应用到一个名为Student的类上。 总之,Attribute特性C#中用于给程序元素添加元数据,以提供额外的信息和行为。它们是一种强大的工具,可以用于实现各种功能和扩展。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [C# 特性Attribute)](https://blog.csdn.net/qq_42335551/article/details/130268405)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [Attribute/特性心得随笔](https://download.csdn.net/download/weixin_38607552/13055291)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值