反射(C# 和 Visual Basic)

特性具有以下属性:

  • 创建自定义特性(C# 和 Visual Basic)

  • 可以将一个或多个特性应用到整个程序集、模块或较小的程序元素(如类和属性)。

  • 特性可以与方法和属性相同的方式接受参数。

  • 使用反射访问特性(C# 和 Visual Basic)

它必须位于所应用于的元素的紧前面并与该元素在同一行。

SerializableAttribute 将特定特征应用于类:

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


DllImportAttribute 特性的方法的声明如下:

using System.Runtime.InteropServices;


...


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


一个声明上可放置多个特性:

using System.Runtime.InteropServices;


...


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


ConditionalAttribute 就是一个可多次使用的特性:

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


说明

DllImportAttribute 才是该特性在 .NET Framework 中的实际名称。

特性参数

例如,这三个特性是等效的:

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

有关默认参数值的信息,请参考各个特性的文档。

特性目标

但是,您也可以显式标识要将特性应用于方法还是它的参数或返回值。

若要显式标识特性目标,请使用下面的语法:

[target : attribute-list]

target 值的列表。

 

C#

Visual Basic

适用对象

assembly

Assembly

整个程序集

module

Module

当前程序集模块(不同于 Visual Basic 模块)

field

不支持

在类或结构中的字段

event

不支持

event

method

不支持

set 属性访问器

param

不支持

set 属性访问器参数

property

不支持

属性

return

不支持

get 属性访问器的返回值

type

不支持

结构、类、接口、枚举或委托

常用特性(C# 和 Visual Basic)

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


下面的示例演示如何在 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; }


说明

AttributeUsage(C# 和 Visual Basic)

以下列表包含特性的几个常见用途:

  • WebMethodAttribute

  • MarshalAsAttribute

  • 描述类、方法和接口的 COM 属性。

  • DllImportAttribute 类调用非托管代码。

  • 在标题、版本、说明或商标方面描述您的程序集。

  • 描述要持久性序列化类的哪些成员。

  • 描述如何映射类成员和 XML 节点以便进行 XML 序列化。

  • 描述方法的安全要求。

  • 指定用于强制安全性的特性。

  • 由实时 (JIT) 编译器控制优化,以便易于调试代码。

  • 获取有关调用方的信息的方法。

相关文章:

  • 2021-12-29
  • 2022-12-23
  • 2022-03-01
  • 2021-11-02
  • 2021-06-12
  • 2021-10-19
  • 2022-01-28
  • 2021-11-24
猜你喜欢
  • 2022-01-12
  • 2021-09-30
  • 2021-07-16
  • 2022-01-10
  • 2022-12-23
  • 2021-07-25
相关资源
相似解决方案