TOC

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

Reflection:

The right Type

Type 类是反射的基础。它是相关程序集、模块或者类型的运行时信息。幸运的是,获得一个对象的类型引用相当简单,因为每个类都继承于 Object 类,而该父类有 GetType() 方法。如果你需要一个有关非实例化类型的信息,你可以使用 typeof() 方法,该方法可以达到同样的功能并且在全局上都是可用的。考虑以下例子,在这个例子中,我们使用这两种方法:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string test = "test";
            Console.WriteLine(test.GetType().FullName);
            Console.WriteLine(typeof(Int32).FullName);
            Console.ReadKey();
        }
    }
}

我们在我们自己的变量上使用 GetType() 方法,之后在已知的 Int32 类型上使用 typeof() 方法。如你所见,两种情况下的结果都是 Type 对象,在这个对象中,我们可以获取 FullName 属性。

在某些时候,你甚至可能只知道你在寻找的类型名称。这种情况下,你必须从正确的程序集中获取它的引用。在接下来的例子中,我们获取一个正在执行的程序集的引用,即获取当前执行代码所在的程序集,之后我们列出它所有的类型:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            Type[] assemblyTypes = assembly.GetTypes();
            foreach(Type t in assemblyTypes)
                Console.WriteLine(t.Name);
            Console.ReadKey();
        }
    }

    class DummyClass
    {
        //Just here to make the output a tad less boring :)
    }
}

这个例子的结果就是两个声明类的名字,即 Program 和 DummyClass,但在更加复杂一点的应用中,这个列表可能会更有趣。在这种情况下,我们只获取类型的名字,但是显然我们可以使用所得的 Type 引用来做更多的事。在接下来的章节中,我会向你展示我们可以使用这个来做什么。


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!