直接展示簡單的示例代碼。
using UnityEngine;
using System.Collections;
using System;
using System.Reflection;
public class GetProperties : MonoBehaviour {
// Use this for initialization
void Start () {
student t=new student();
Getmember(t);
System.Object o = new System.Object();
}
// Update is called once per frame
void Update () {
}
void Getmember(student t)
{
Type type =t.GetType();
//foreach(PropertyInfo p in type.GetProperties())
//{
// print(p.Name + "=" + p.GetValue(t, null));
//}
//foreach(MemberInfo m in type.GetMembers())
//{
// print(m.Name);
//}
FieldInfo[] finfos = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach(FieldInfo finfo in finfos)
{
print("字段名稱" + finfo.Name + " 字段類型:" + finfo.FieldType.ToString());
}
}
}
class student
{
private string name;
private int age;
public int id;
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public student(string n, int a, int i)
{
name = n;
Age = a;
id = i;
}
}
示例看起來蠻簡單的嘛。
反射能夠獲取一個未知類裏面的所有的方法,屬性,字段,構造函數等等。在做一些插件的時候這個是很好用的功能。unity 內置的週期函數例如:Awake, start ,Update 等的方法也是反射實現的。在使用的時候要注意的是反射也挺耗內存的。所以在unity裏面,如果有空的Update,Start之類的方法,一定要清理掉,避免不必要的性能消耗。