反射的常用类:
Type类:是设计用来包含类型的特性,可以获取程序使用的类型的信息(即:可以获得一个类包含的成员与方法)
功能:使用Type类对象,可以查看一个类中所有的非私有字段、方法、属性(通过相关的参数也可以查看私有的字段、不常用)
Assembly类:得到一个程序集中的反射信息
功能:加载程序集
Assembly.Load(); //不推荐使用
Assembly.LoadFrom("程序集的完整路径名称");
Type类:
Type实例可以获取类名称、所属命名空间、是否为公共类等以及类的字段、属性、方法等信息。
例如:
Person per = new Person();
Type typePer = per.GetType();
FieldInfo[] infoArray = typePer.GetFields(); //字段(非私有)
PropertyInfo[] propArray = typePer.Getproperties(); //属性
MethodInfo[] methodArray = typeObj.GetMethods(); //方法
源代码:
Person类:
/***
*实体类:被分析的对象
*
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace chapter30Type类的常用方法
{
public class Person
{
//字段
public string Name;
public int Age;
private int _ID;
//属性
public int ID
{
get { return _ID; }
set { _ID = value; }
}
//方法
public void DisplayID()
{
Console.WriteLine(ID);
}
public void DisplayName()
{
Console.WriteLine(Name);
}
public void DisplayAge()
{
Console.WriteLine(Age);
}
主程序:
/***
*反射的概念:
*1.反射是通过程序,了解以及调用“程序集”中程序的相关属性、字段、方法
*
*
*
*
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace chapter30Type类的常用方法
{
class Program
{
//打印类的普通信息
public void Test1()
{
Person per = new Person();
Type typePersonObj = per.GetType();
//显示类的名称
Console.WriteLine(typePersonObj.Name);
//显示类所属的命名空间
Console.WriteLine(typePersonObj.Namespace);
//显示类所属的程序集
Console.WriteLine(typePersonObj.Assembly);
//获取类是否为公共、密封、私有
Console.WriteLine(typePersonObj.IsPublic);
Console.WriteLine(typePersonObj.IsSealed);
Console.WriteLine(typePersonObj.IsPrimitive);
}
//打印类的属性、字段、方法
public void Test2()
{
Person per = new Person();
Type typePersonObj = per.GetType();
//获取字段信息
FieldInfo[] fileArray = typePersonObj.GetFields();
foreach (var item in fileArray)
{
Console.WriteLine(item.Name);
}
Console.WriteLine("-----------------");
//获取属性信息
PropertyInfo[] proInfo = typePersonObj.GetProperties();
foreach (var item in proInfo)
{
Console.WriteLine(item.Name);
}
Console.WriteLine("----------------");
//获取方法信息
MethodInfo[] methodArray = typePersonObj.GetMethods();
foreach (MethodInfo item in methodArray)
{
Console.WriteLine(item.Name);
}
}
static void Main(string[] args)
{
Program obj = new Program();
//obj.Test1();
obj.Test2();
}
}
}
}
}