C#_Attribute


Attribute

Attribute, generally translated into characteristics (distinguished from Property attributes).
It provides a powerful way to associate metadata (declarative information) with code (assemblies, types, methods, properties, etc.). After the Attribute is associated with the program entity , the Attribute can be queried at runtime using reflection technology.

Metadata
Metadata is data that describes data.
In the C# programming environment, it refers to the characteristics used to describe program code.
Witty friends will ask, describe the program code? That's not a comment.
There is an essential difference here. Comments usually do not affect the execution of the program, and the compiler ignores comments during compilation; metadata is data, which can be queried and manipulated when the program is running through techniques such as reflection.

Attribute has the following properties:

  • Attribute will add metadata to the program. Metadata is information about types defined in a program. All .NET assemblies contain a specified set of metadata for describing the types and class members defined in the program. You can add a custom Attribute to specify additional information required.
  • One or more Attributes can be applied to an entire assembly, a module, or a smaller program element (class, attribute, etc.).
  • Attributes can receive parameters like methods and properties.
  • You can use reflection in your program to inspect metadata.

Reflection provides objects of type Type to describe assemblies, modules, and types. You can use reflection to dynamically create instances of classes, bind classes to existing objects, or obtain types from existing objects and call their methods or access their fields and properties. If you use Attributes in your code, you can access them using reflection.

The following is a simple reflection example that uses the GetType() method (available for all classes that inherit from Object) to get the type of a variable:

Note
Before using, add using system; and using System.Reflection; at the top of the .cs file

// using GetType to obtain type information
int i = 42;
Type type = i.GetType();
Console.WriteLine(type);

Output: System.Int32

The following example uses reflection to get the full name of the loaded assembly:

// using Reflection to get information of an Assembly
Assembly info = typeof(int).Assembly;
Console.WriteLine(info);

Default: System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e

Note that
the C# keywords protected and internal have no meaning in intermediate language (IL) and will not work in the reflection API. The corresponding terms in IL are Family and Assembly . To identify internal methods using reflection, use the IsAssembly property. To identify protected internal methods, use IsFamilyOrAssembly.

Use Attributes

Attributes can be placed on almost any declaration, although a particular Attribute may limit the types of declarations for which it is valid. In C#, you can specify an Attribute by enclosing the Attribute name in square brackets [] and placing it on the entity declaration to which the Attribute applies.

In the following example, the SerializableAttribute Attribute is used to assign a property to a class (objects of this class will be serialized):

[Serializable]
public class SampleClass
{
    
    
	// objects of this type can be serialized.
}

The following example declares a method with the DllImportAttribute attribute:

[System.Runtime.InteropServices.DllImport("user32.dll")]
extern static void SampleMethod();

Multiple Attributes can also be placed in a statement, as follows:

void MethodA([In][Out] ref double x) {
    
     }
void MethodB([Out][In] ref double x) {
    
     }
void MethodC([In, Out] ref double x) {
    
     }

Some Attributes can also be specified multiple times for a given entity. The following is an example of Attribute with multiple uses (ConditionalAttribute):

[Conditional("DEBUG"), Conditional("TEST1")]
void TraceMethod()
{
    
    
	// ...
}

Note
By convention, all Attribute names end with "Attribute" to distinguish them from other items in the .NET library. However, when using Attribute in code, you don't need to specify the Attribute suffix. For example [DllImport] is equivalent to [DllImportAttribute], but DllImportAttribute is the actual name of Attribute in the .NET class library.

Attribute parameters

Many Attributes have parameters, which may be positional, unnamed, or named. Positional parameters must be specified in a certain order and cannot be omitted. Named parameters are optional and may be specified in any order. The following three Attributes are equivalent:

[DllImport("user32.dll")]
[DllImport("user32.dll", SetLastError=false, ExactSpelling=false)]
[DllImport("user32.dll", ExactSpelling=false, SetLastError=false)]

The first parameter DLL name, which is a positional parameter, always ranks first; other parameters are named parameters. In that case, the two default parameters default to false and can therefore be omitted. The positional arguments correspond to the arguments (list) of the Attribute constructor. Named or optional parameters correspond to Attribute properties (property) or fields (field).

Attribute target

The target of Attribute refers to the entity to which the Attribute is applied. Attribute can be applied to a class, a specific method, or an entire assembly. By default, the Attribute is applied to the element after it. But you can also explicitly identify whether an Attribute is applied to a method, or to its parameters or its return value.

To explicitly identify an Attribute target, use the following syntax:

[target : attribute-list]

The possible values ​​for target are shown in the table below:

Target value application target
assembly entire assembly
module current program module
field fields in a class or struct
event event
method method or get and set property accessors
param method parameter or set property accessor parameter
property Attributes
return method return value, property index or get property accessor
type struct, class, interface, enum, or delegate

You can specify the field target value to apply the Attribute to the background field created by the auto-implemented property.

The following examples show how to apply Attributes to assemblies and modules.

using System;
using System.Reflection;
[assembly: AssemblyTitleAttribute("Production assembly 4")]
[module: CLSCompliant(true)]

The following example shows how to apply Attribute to methods, method parameters and method return values ​​in C#.

// default: applies to method
[ValidatedContract]
int Method1() {
    
     return 0; }

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

// applies to parameter
int Method3([ValidatedContract] string contract) {
    
     return 0; }

// applies to return value
[return: ValidatedContract]
int Method4() {
    
     return 0; }

Note
The return target must be specified regardless of which targets the ValidatedContract is defined to apply to, even if the ValidatedContract is defined to apply only to the return value. In other words, the compiler will not use AttributeUsage information to resolve ambiguous Attribute targets.

Common uses of Attribute

Common uses of Attribute in code are listed below:

  • Use the WebMethod Attribute in the Web service to mark the method to indicate that the method can be called through the SOAP protocol.
  • Describes how method parameters are encapsulated when interacting with native code.
  • COM properties that describe classes, methods, and interfaces.
  • Use the DllImportAttribute class to call unmanaged code.
  • Describe the assembly using title, version, description, or branding.
  • Describes serializing class members for persistence.
  • Describes how to map between class members and XML nodes for XML serialization.
  • Describe the security requirements for the method.
  • Specifies the attributes used to enforce security.
  • Controls the JIT's optimizations to make code easy to debug.
  • Get information about the method caller.

reflection overview

Reflection is useful in the following situations:

  • When you need to access properties in program metadata.
  • When inspecting and instantiating a class in an assembly.
  • Build new classes at runtime. Use the classes in System.Relection.Emit.
  • Performs late binding, accessing methods on classes created at runtime.

Guess you like

Origin blog.csdn.net/BadAyase/article/details/130708962