使用Type类以前需要引用反射的命名空间:
using System.Reflection;
以下是完整代码:
public class ReflectionDemo : MonoBehaviour
{
void Start()
{
A a = new A();
B b = new B();
A[] abArray=new A[] { a, b };
foreach(A v in abArray)
{
Type t = v.GetType();
Debug.Log("Object type : " + t.Name);
FieldInfo[] fi = t.GetFields();
foreach(FieldInfo f in fi)
{
Debug.Log("Field : " + f.Name);
}
}
}
}
class A
{
public int AField = 0;
}
class B : A
{
public int BField = 0;
}
输出结果: