网上摘要概述
反射指程序可以访问、检测和修改它本身状态或行为的一种能力。
程序集包含模块,而模块包含类型,类型又包含成员。反射则提供了封装程序集、模块和类型的对象。
您可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型。然后,可以调用类型的方法或访问其字段和属性。
实际操作
Untiy环境
一,创建反射对象
1.通过typeof获取:typeof(类名)
Type gameobjects = typeof(GameObject);
Debug.Log(gameobjects);
打印结果:
UnityEngine.GameObject
UnityEngine.Debug:Log (object)
2.通过对象获取:对象名.GetType()
Type transforms = transform.GetType();
Debug.Log(transforms.Assembly);
打印结果:
UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
UnityEngine.Debug:Log (object)
3.通过静态方法获取:Type.GetType("程序集名字符串")
Type types = Type.GetType("UnityEngine.GameObject, UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
Debug.Log(types);
打印结果:
UnityEngine.GameObject
UnityEngine.Debug:Log (object)
二,演示实例
实例一
1.在命名空间02创建一个类,创建2个私有字段和2个私有方法
namespace namespace02
{
public class MyInterfaceOne
{
private string _Name="私有的";
private int number;
private void show1()
{
//方法被执行至答应
Debug.Log("通过反射实现方法'show1'方法");
}
private void show2()
{
//方法被执行至答应
Debug.Log("通过反射实现方法'show2'方法");
}
}
}
2.在命名空间01创建一个脚本
namespace namespace01
{
public class TypeDemo : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//通过反射找到Type对象
Type type = typeof(namespace02.MyInterfaceOne);
//找到MyInterfaceOne 的私有成员并遍历
FieldInfo[] fieldInfo= type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
for (int i=0;i<fieldInfo.Length;i++) {
Debug.Log(fieldInfo[i].Name);
}
打印结果:
//找到MyInterfaceOne私有方法并遍历
MethodInfo[] memberInfos= type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
for (int i = 0; i < memberInfos.Length; i++)
{
Debug.Log(memberInfos[i].Name);
}
打印结果:
//获取私有成员变量
object fielvalue= fieldInfo[0].GetValue(new namespace02.MyInterfaceOne());
Debug.Log(fielvalue);
//修改私有成员变量
namespace02.MyInterfaceOne myInterfaceOne = new namespace02.MyInterfaceOne();
fieldInfo[0].SetValue(myInterfaceOne, "通过反射修改");
Debug.Log("fielvalue的值:" + fielvalue);
//调用私有成员方法Invoke (实例化对象,参数/null)
memberInfos[0].Invoke(new namespace02.MyInterfaceOne(), null);
打印结果:
}
}
}