在.NET中的反射

.NET Framework反射API允许您在运行时以编程方式获取程序集类型信息。
我们还可以通过使用.NET反射来实现后期绑定。

在运行时,反射机制使用PE文件读取有关程序集的信息。反射使您能够使用编译时不可用的代码。NET反射允许应用程序收集关于自身的信息,也允许对自身进行操作。它可以有效地用于查找程序集中的所有类型和/或者动态调用程序集中的方法。这包括有关对象的类型、属性、方法和事件的信息。通过反射,我们可以动态地创建类型的实例,将类型绑定到现有对象,或者从现有对象获取类型并调用其方法,或者访问其字段和属性。我们也可以使用反射来访问属性信息。

.NET有一个强大的机制称为.NET反射,它不仅允许您内省类型,而且在运行时引发这些类型的方法。尽管与直接访问方法、属性或者字段相比,.NET反射在.NET反射中检索类型信息的过程很慢,但在节省使用时,.NET反射提供了代码和控件的动态执行。所有类型及其方法都存储在程序集中。

C# .NET 反射示例

using System;

using System.Collections.Generic;

using System.Text;

using System.Reflection; 
 

namespace ReflectionTest

{

    class Program

    {

       private static int a = 5, b = 10, c = 20;

        static void Main(string[] args)

        {

            Console.WriteLine("a + b + c = " + (a + b + c));

            Console.WriteLine("请输入要修改变量的名称:");

            string varName = Console.ReadLine();

            Type t = typeof(Program);

            FieldInfo fieldInfo = t.GetField(varName, BindingFlags.NonPublic | BindingFlags.Static);

            if (fieldInfo != null)

            {

                Console.WriteLine("当前值为 " + fieldInfo.Name + " is " + fieldInfo.GetValue(null) + ". 请输入新值:");

          string newValue = Console.ReadLine();

          int newInt;

          if (int.TryParse(newValue, out newInt))

          {

            fieldInfo.SetValue(null, newInt);

            Console.WriteLine("a + b + c = " + (a + b + c));

             }

            Console.ReadKey();

            }

        }

    }

}
日期:2020-04-11 23:03:43 来源:oir作者:oir