答案:通过反射命名空间中的类以及 System.Type,您可以获取有关已加载的程序集和在其中定义的类型(如类、接口和值类型)的信息。您也可以使用反射在运行时创建类型实例,然后调用和访问这些实例。反射概述
公共语言运行库加载器管理应用程序域。这种管理包括将每个程序集加载到相应的应用程序域以及控制每个程序集中类型层次结构的内存布局。
程序集包含模块,而模块包含类型,类型又包含成员。反射则提供了封装程序集、模块和类型的对象。您可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型。然后,可以调用类型的方法或访问其字段和属性。反射通常具有以下用途:
[C#]
// Get the mscorlib assembly in which the object is defined.
Assembly a = typeof(Object).Module.Assembly;
[C#]
// Load an assembly using its file name.
Assembly a = Assembly.LoadFrom ("MyExe.exe");
// Get the type names from the assembly.
Type [] types2 = a.GetTypes ();
foreach (Type t in types2)
{
Console.WriteLine (t.FullName);
}
[C#]
// This program lists all the public constructors
// of the System.String class.
using System;
using System.Reflection;
class ListMembers {
public static void Main(String[] args) {
Type t = typeof(System.String);
Console.WriteLine ("Listing all the public constructors of the {0} type", t);
// Constructors
ConstructorInfo[] ci = t.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
Console.WriteLine ("//Constructors");
PrintMembers (ci);
}
public static void PrintMembers(MemberInfo [] ms) {
foreach (MemberInfo m in ms) {
Console.WriteLine ("{0}{1}", " ", m);
}
Console.WriteLine();
}
}
[C#]
using System;
using System.IO;
using System.Reflection;
class Mymemberinfo
{
public static void Main(string[] args)
{
Console.WriteLine ("\nReflection.MemberInfo");
// Get the Type and MemberInfo.
Type MyType =Type.GetType("System.IO.File");
MemberInfo[] Mymemberinfoarray = MyType.GetMembers();
// Get and display the DeclaringType method.
Console.WriteLine("\nThere are {0} members in {1}.",
Mymemberinfoarray.Length, MyType.FullName);
Console.WriteLine("{0}.", MyType.FullName);
if (MyType.IsPublic)
{
Console.WriteLine("{0} is public.", MyType.FullName);
}
}
}
[C#]
// This code displays information about the GetValue method of FieldInfo.
using System;
using System.Reflection;
class MyMethodInfo {
public static int Main() {
Console.WriteLine("Reflection.MethodInfo");
// Get and display the Type.
Type MyType = Type.GetType("System.Reflection.FieldInfo");
// Specify the member for which you want type information here.
MethodInfo Mymethodinfo = MyType.GetMethod("GetValue");
Console.WriteLine(MyType.FullName + "." + Mymethodinfo.Name);
// Get
上一个:在.NET运行时了解类型信息(2) Paul_Ni(原作)
下一个:使用 .NET的IO(4) Paul_Ni(原作)