反射 (C#)Reflection (C#)

反射提供描述程序集、模块和类型的对象(Type 类型)。Reflection provides objects (of type Type) that describe assemblies, modules, and types. 可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型,然后调用其方法或访问器字段和属性。You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. 如果代码中使用了特性,可以利用反射来访问它们。If you are using attributes in your code, reflection enables you to access them. 有关更多信息,请参阅特性For more information, see Attributes.

下面一个简单的反射示例,使用方法 GetType()(被 Object 基类的所有类型继承)以获取变量类型:Here's a simple example of reflection using the GetType() method - inherited by all types from the Object base class - to obtain the type of a variable:

备注

请确保在 .cs 文件顶部添加 using System;using System.Reflection;Make sure you add using System; and using System.Reflection; at the top of your .cs file.

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

输出为:System.Int32The output is: System.Int32.

下面的示例使用反射获取已加载的程序集的完整名称。The following example uses reflection to obtain the full name of the loaded assembly.

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

输出为:System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798eThe output is: System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e.

备注

C# 关键字 protectedinternal 在 IL 中没有任何意义,且不会用于反射 API 中。The C# keywords protected and internal have no meaning in IL and are not used in the reflection APIs. 在 IL 中对应的术语为“系列”和“程序集”。The corresponding terms in IL are Family and Assembly. 若要标识 internal 使用反射的方法,请使用 IsAssembly 属性。To identify an internal method using reflection, use the IsAssembly property. 若要标识 protected internal 方法,请使用 IsFamilyOrAssemblyTo identify a protected internal method, use the IsFamilyOrAssembly.

反射概述Reflection overview

反射在以下情况下很有用:Reflection is useful in the following situations:

更多相关信息:For more information:

另请参阅See also