一,定义
反射技术,能够让托管代码在运行时查看元数据以及代码的各方面信息。
二,常用方法
1,获取对象方法(必须以Public修饰的方法,不包括构造函数);
2,获取对象属性;
3,获取对象的父类;
附示例代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
/// <summary>
/// 基类
/// </summary>
public class Base
{
}
/// <summary>
/// 继承Base的子类
/// </summary>
public class Child : Base
{
private int num = 1;
public Child()
{
}
public int Num
{
get
{
return num;
}
set
{
this.num = value;
}
}
//在获取对象方法时,非Public修饰的方法是无法取得的,但包括构造函数
private void testMethod1()
{
}
public void testMethod2()
{
}
}
public class Program
{
Child c = new Child();
static void Main(string[] args)
{
Program p = new Program();
System.Type cType = p.c.GetType();
//获取对象方法
MethodInfo[] methods = cType.GetMethods();
Console.WriteLine("方法列表:");
foreach (MethodInfo m in methods )
{
Console.WriteLine(m.Name );
}
//获取对象属性
PropertyInfo[] propertys = cType.GetProperties();
Console.WriteLine("属性列表:");
foreach (PropertyInfo ps in propertys )
{
Console.WriteLine(ps.Name );
}
//获取对象基类
System.Type parent = cType.BaseType;
Console.WriteLine("对象层次结构:");
Console.Write(cType .FullName );
while (parent !=null )
{
Console.Write("->" + parent .Name);
parent = parent.BaseType;
}
Console.Read();
}
}
运行结果:
方法列表:
get_Num
set_Num
testMethod2
GetType
ToString
Equals
GetHashCode
属性列表:
Num
对象层次结构:
Child->Base->Object