TOC

This article is currently in the process of being translated into Chinese (~77% done).

Reflection:

Reflection introduction

维基百科对反射是这样解释的:在计算科学邻域中,所谓反射,指的是计算机程序可以观察和修改自身的结果和行为的过程。这也是 C# 中反射机的工作方式。可能你并没有意识到这一点,但是在运行时有能力检查和修改应用程序的相关信息有着相当大的潜力。反射,它既是一个通用的术语,但也是 C# 反射功能的实际名称,且它效果好易于使用。在接下来的几个章节内,我们将深入介绍它的工作原理,以及向你提供一些很酷的例子,这些例子能够向你展示反射的用途。

然而,为了让你有兴趣地开始学习,这里介绍一个小例子。这个例子解决了我从许多新手在任意编程语言看到的问题:在运行时当仅知道变量的名字时,如何才能修改变量的值呢?接下来这个例子就给出了一种解决方案,并通过阅读接下来的章节内容来了解所使用的不同技术。

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("Please enter the name of the variable that you wish to change:");
            string varName = Console.ReadLine();
            Type t = typeof(Program);
            FieldInfo fieldInfo = t.GetField(varName, BindingFlags.NonPublic | BindingFlags.Static);
            if(fieldInfo != null)
            {
                Console.WriteLine("The current value of " + fieldInfo.Name + " is " + fieldInfo.GetValue(null) + ". You may enter a new value now:");
                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();
            }
        }
    }
}

试着运行这段代码并看下它是如何工作的。除了我们使用反射的几行代码之外,这个例子非常地简单。现在,请在下一章节查看这个例子的工作原理吧。


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!