反射一词出现在面向对象程序设计中,主要用于获取变量或类的相关信息,比如变量的类型,类的构造方法,字段信息,成员函数信息,属性信息。
主要使用Type类中的GetType方法
下面示例演示如何列出String类的构造函数- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Reflection;
- namespace Reflection
- {
- class Program
- {
- public static void PrintMembers(MemberInfo[] ms) {
- foreach (MemberInfo m in ms) {
- Console.WriteLine("{0}{1}"," ",m);
- }
- Console.WriteLine();
- }
- static void Main(string[] args)
- {
- Type t = typeof(System.String);
- Console.WriteLine("Listint all the public constructors of the {0} type",t);
- ConstructorInfo[] ci = t.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
- Console.WriteLine("//Constructors");
- PrintMembers(ci);
- Console.ReadKey();
- }
- }
- }
复制代码 使用MemberInfo、MethodInfo、FieldInfo、PropertyInfo对象可以获得有关类型的方法、属性、事件、字段的信息。
下面就MemberInfo对象做简单演示- static void Main(string[] args)
- {
- Console.WriteLine("\nReflection.MemberInfo");
- Type MyType = Type.GetType("System.IO.File");
- MemberInfo[] Mymemberinfoarray = MyType.GetMembers();
- 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);
- }
- foreach (MemberInfo m in Mymemberinfoarray) {
- Console.WriteLine(m.ToString());
- }
- Console.ReadKey();
- }
复制代码 |