系列文章目录
前言
昨天理解了委托和事件,今天来学习一下反射
一、反射是什么
反射在Java中是指获取运行状态下的类的信息的方法,同样,在C#也是如此:
程序正在运行时,可以查看其它程序集或者自身的元数据,一个运行的程序查看本身或者其它程序的元数据的行为就叫做反射
二、反射的作用
因为反射可以在程序编译后获得信息,所以它提高了程序的拓展性和灵活性
- 程序运行时得到所有元数据,包括元数据的特性
- 程序运行时,实例化对象,操作对象
- 程序运行时创建新对象,用这些对象执行任务
三,反射的语法
1.Type的获取
Type(类的信息类)它是反射功能的基础
它是访问元数据的主要方式,使用 Type 的成员获取有关类型声明的信息,有关类型的成员(如构造函数、方法、字段、属性和类的事件)
获取Type示例:
//1.object中的 GetType()可以获取对象的Type
int a = 4;
Type type = a.GetType();
Console.WriteLine(type);
//2.通过typeof关键字 传入类名 也可以得到对象的Type
Type type = typeof(int);
Console.WriteLine(type);
//3.通过类的名字 也可以获取类型,这里需要注意的是类名必须包含命名空间,否则会找不到
Type type = Type.GetType("System.Int32");
Console.WriteLine(type);
2.反射应用场景
-
得到类的程序集信息
Console.WriteLine(type.Assembly);
-
获取类中的所有公共成员
//获取Type
Type t = typeof(Test);
//获取所有公共成员
//注意:这里需要引用命名空间 using System.Reflection;
MemberInfo[] infos = t.GetMembers();
for (int i = 0; i < infos.Length; i++)
{
Console.WriteLine(infos[i]);
}
- 获取类的公共构造函数并调用
- 先获取所有构造函数
- 获取其中一个构造函数,并执行
- 有参构造
- 无参构造
这里是获取
ConstructorInfo[] ctorinfos = t.GetConstructors();
for (int i = 0; i < ctorinfos.Length; i++)
{
Console.WriteLine(ctors[i]);
}
无参构造
ConstructorInfo info = t.GetConstructor(new Type[0]);
//执行无参构造 无参构造 没有参数 传null
Test obj = info.Invoke(null) as Test;
Console.WriteLine(obj.j);
有参构造
ConstructorInfo info3 = t.GetConstructor(new Type[] { typeof(int), typeof(string) });
obj = info3.Invoke(new object[] { 4, "Hello World" }) as Test;
Console.WriteLine(obj.str);
- 获取类的公共成员变量
//获取所有成员变量
FieldInfo[] fieldInfos = t.GetFields();
for (int i = 0; i < fieldInfos.Length; i++)
{
Console.WriteLine(fieldInfos[i]);
}
//获取指定名称的公共成员变量,这里只是获取到对象,不是值
FieldInfo infoJ = t.GetField("zhmen");
Console.WriteLine(infoJ);
- 还可以通过反射获取设置对象的值
Test test = new Test();
test.age = 999999;
test.name= "你好";
//通过反射 获取对象的某个变量的值
Console.WriteLine(infoJ.GetValue(test));
//通过反射 设置指定对象的某个变量的值,就是给test对象的j,设置100,
infoJ.SetValue(test, 100);
Console.WriteLine(infoJ.GetValue(test));
- 获取类的公共成员方法
//通过Type类中的 GetMethod方法 得到类中的方法
//MethodInfo 是方法的反射信息
Type strType = typeof(string);
MethodInfo[] methods = strType.GetMethods();//获取String类中的所有的公共方法
for (int i = 0; i < methods.Length; i++)
{
Console.WriteLine(methods[i]);
}
//若存在方法重载 用Type数组表示参数类型
MethodInfo subStr = strType.GetMethod("Substring",new Type[] { typeof(int), typeof(int) });
//调用该方法,注意:如果是静态方法 Invoke中的第一个参数传null
string str = "Hello,World!";
//第一个参数相当于是哪个对象要执行这个成员方法
object result = subStr.Invoke(str, new object[] { 7, 5 });
Console.WriteLine(result);
3.其他的反射语法
这里列举比较常用的:
- 枚举:
GetEnumName()
,GetEnumNames()
- 事件:
GetEvent()
,GetEvents()
- 接口:
GetInterface()
,GetInterfaces()
- 属性:
GetProperty()
,GetPropertys()