1.含义
反射指程序可以访问、检测和修改它本身状态或行为的一种能力。
程序集包含模块,而模块包含类型,类型又包含成员。反射则提供了封装程序集、模块和类型的对象。
2.优缺点
1.优点
1.提供程序的灵活性和扩展性
2.降低耦合性,提高自适应能力
3.允许程序场景和控制任意类对象,不需要提前硬编码目标类
2.缺点
1、性能问题:使用反射基本上是一种解释操作,用于字段和方法接入时要远慢于直接代码。因此反射机制主要应用在对灵活性和拓展性要求很高的系统框架上,普通程序不建议使用。
2、使用反射会模糊程序内部逻辑;程序员希望在源代码中看到程序的逻辑,反射却绕过了源代码的技术,因而会带来维护的问题,反射代码比相应的直接代码更复杂
3.主要使用场景与用途
1.主要使用场景与命名空间
1.运行时需要创建新的对象
2.执行后期绑定,访问在运行时创建的类型方法
2.主要用途
1.Assembly:定义和加载程序集
2.FieldInfo:数据成员信息对象
3.MethodInfo:函数成员信息对象
4.命名空间
System.Reflection
System.Type 访问被反射数据类型的元数据
System.Reflection.Assembly 用于访问给定的程序集信息,或者将程序集信息加载到程序中
5.实例
class Program
{
static void Main(string[] args)
{
//获取string类型 利用typeof获取
Type t1 = typeof(string);
Console.WriteLine(t1);
string a = "abc";
Type t2 = a.GetType();
Console.WriteLine(t2);
Type t3 = Type.GetType("System.String");
Console.WriteLine(t3);
//通过gettype获取变量类型
int i = 0;
Type t4 = i.GetType();
Console.WriteLine(t4);
Type t5 = Type.GetType("Test");
Console.WriteLine(t5);
Type t6 = typeof(Test);
Console.WriteLine(t6);//Test
//创建对象
//常规创建对象
//Test t = new Test();
//通过反射创建对象
object obj = Activator.CreateInstance(t6);
//获取数据成员
FieldInfo[] fi = t6.GetFields();
foreach (var item in fi)
{
Console.WriteLine(item);
}
//通过GetField找到指定的目标变量 通过SetValue和GetValue设置值
FieldInfo ageInfo = t6.GetField("age");
ageInfo.SetValue(obj, 5);
Console.WriteLine(ageInfo.GetValue(obj));
Console.WriteLine(((Test)(obj)).age);//强转
Console.WriteLine((obj as Test).age);//强转
//访问成员函数
MethodInfo[] mi = t6.GetMethods();
foreach (var item in mi)
{
Console.WriteLine(item);
}
//访问无参无返回值成员函数
MethodInfo m1 = t6.GetMethod("TestMethod1");
m1.Invoke(obj, null);//对象名.函数名()
//访问无参有返回值成员函数
MethodInfo m2 = t6.GetMethod("TestMethod2");
object n = m2.Invoke(obj, null);//对象名.函数名()
Console.WriteLine(n);
//访问带参且有返回值成员函数
MethodInfo m3 = t6.GetMethod("TestMethod3");
object[] parameters = new object[3];
parameters[0] = 5;
parameters[1] = 1;
parameters[2] = "hello world";
object n1 = m3.Invoke(obj, parameters);
Console.WriteLine(n1);
}
}
class Test
{
public int age;
public int sex;
public string name;
public void TestMethod1()
{
Console.WriteLine("方法1");
}
public int TestMethod2()
{
Console.WriteLine("方法2");
return 1;
}
public int TestMethod3(int age, int sex, string name)
{
Console.WriteLine("方法3" + age + "," + sex + "," + name);
this.age = age;
this.sex = sex;
this.name = name;
return -1;
}
}