1.反射简介
2.反射示例
1.反射简介
1).反射式程序运行时可以看自己的结构(比如: 类, 方法, 属性等), 并能操作这些结构; 反射的核心命名空间
System.Reflection, 核心类是Type(所有类型信息的入口)
2).反射的核心使用场景
a.动态创建对象
b.动态调用方法
c.访问私有成员
d.读取自定义特性
2.反射示例
1).准备测试类
先定义一个基础类, 用于后续反射操作
using System;
using System.Reflection;
public class Person
{
public string Name;
private int _age;
public int Age
{
get => _age;
set { if (value > 0) _age = value; }
}
public Person()
{
Name = "未知";
_age = 0;
}
public Person(string name, int age)
{
Name = name;
_age = age;
}
public string SayHello()
{
return $"你好,我是{Name},今年{_age}岁!";
}
private string GetSecret()
{
return $"我的秘密:{Name}的年龄是{_age}";
}
}
2).获取Type对象(反射的入口)
Type是反射的核心, 获取它有3种常用方式
Type type1 = typeof(Person);
Person p = new Person();
Type type2 = p.GetType();
Type type3 = Type.GetType("Person");
Console.WriteLine($"类型名称:{type1.Name}");
Console.WriteLine($"是否是类:{type1.IsClass}");
3).动态创建对象
object obj1 = Activator.CreateInstance(type1);
Person p1 = (Person)obj1;
Console.WriteLine($"无参实例:{p1.Name},{p1.Age}");
Type[] paramTypes = new Type[] { typeof(string), typeof(int) };
ConstructorInfo constructor = type1.GetConstructor(paramTypes);
object[] paramValues = new object[] { "张三", 25 };
object obj2 = constructor.Invoke(paramValues);
Person p2 = (Person)obj2;
Console.WriteLine($"有参实例:{p2.Name},{p2.Age}");
4).访问字段和属性
FieldInfo nameField = type1.GetField("Name");
Console.WriteLine($"公共字段Name:{nameField.GetValue(p2)}");
nameField.SetValue(p2, "李四");
Console.WriteLine($"修改后Name:{nameField.GetValue(p2)}");
FieldInfo ageField = type1.GetField("_age", BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine($"私有字段_age:{ageField.GetValue(p2)}");
ageField.SetValue(p2, 30);
PropertyInfo ageProp = type1.GetProperty("Age");
Console.WriteLine($"属性Age:{ageProp.GetValue(p2)}");
ageProp.SetValue(p2, 35);
Console.WriteLine($"修改后Age:{ageProp.GetValue(p2)}");
5).动态调用方法
MethodInfo sayHelloMethod = type1.GetMethod("SayHello");
object result1 = sayHelloMethod.Invoke(p2, null);
Console.WriteLine(result1);
MethodInfo secretMethod = type1.GetMethod("GetSecret", BindingFlags.NonPublic | BindingFlags.Instance);
object result2 = secretMethod.Invoke(p2, null);
Console.WriteLine(result2);