反射(C# 和 Visual Basic)

反射提供了描述程序集、模块和类型的对象(Type 类型)。 可以使用反射动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性。 如果代码中使用了特性,可以利用反射来访问它们。 有关更多信息,请参见 利用特性扩展元数据

下面是使用静态方法 GetType(从 Object 基类派生的所有类型都继承该方法)获取变量类型的简单反射示例:

' Using GetType to obtain type information: 
Dim i As Integer = 42
Dim type As System.Type = i.GetType()
System.Console.WriteLine(type)
// Using GetType to obtain type information: 
int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);

输出为:

System.Int32

下面的示例使用反射获取已加载的程序集的完整名称。

' Using Reflection to get information from an Assembly: 
Dim info As System.Reflection.Assembly = GetType(System.Int32).Assembly
System.Console.WriteLine(info)
// Using Reflection to get information from an Assembly:
System.Reflection.Assembly info = typeof(System.Int32).Assembly;
System.Console.WriteLine(info);

输出为:

mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

备注

C# 关键字 protected 和 internal 在 IL 中没有意义并且在反射 API 中不使用。IL 中对应的术语为“家族”和“程序集”。若要使用反射来标识 internal 方法,请使用 IsAssembly 属性。若要标识 protected internal 方法,请使用 IsFamilyOrAssembly

反射概述

反射在下列情况下很有用:

相关章节

有关更多信息:

请参见

概念

C# 编程指南

其他资源

Visual Basic 编程指南

应用程序域(C# 和 Visual Basic)

公共语言运行时中的程序集