class 中的变量字段中的 GetValue()

GetValue() from a variable field inside a class

假设我有一个简单的 class:

 public class TestScript : MonoBehaviour {
      public Vector3 myVector3;
 }

现在我想遍历此 class 实例的字段并访问此字段的字段(Field-Ception!)并将值分配给正确类型的变量,有效地"wrapping" 字段,以便它可以被序列化。在这里,我将到达 Vector3 字段 "myVector3",到达它后,遍历它的字段并将它们的值分配给三个浮点数(Vector3 由什么组成)。

有问题吗? fieldinfo.GetValue() returns 类型 MonoField!如果我使用 fieldinfo.FieldType,它 returns Vector3,但这对我没有帮助,因为我需要值 :/

TestScript myTestScript;//an instance of the MonoBehaviour class
const BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
 //the fields... only 1 in this case (myVector3)
 FieldInfo[] fields = myTestScript.GetType().GetFields(flags);

 //store Type...
 var tp = myTestScript.GetType();
 //iterate over the fields
 foreach FieldInfo field in fields) {

      if (field != null) {
           //check if the field is of Type Vector3
           if(field.FieldType == typeof(Vector3)) {
                const BindingFlags flags_v3 = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
                //the following will give me an array of FieldInfo 
                //with Type MonoField, but I need the 
                //actual x, y and z (floats) fields!
                FieldInfo[] fields_v3 = field.GetType().GetFields(flags);
                //added with edit:
                foreach(FieldInfo field_v3 in fields_v3) {
                    object value = field_v3 .GetValue(field)//the line in question... Since field.GetType returns MonoFields instead of the Vector3, I can not access the Vector3 Type's x y z fields/values.
                }
           }
      }
 }

field.GetType() returns 实际反射对象的类型,在本例中为 MonoField。使用 field.FieldType,此 属性 包含字段本身存储的值的类型:

FieldInfo[] fields_v3 = field.FieldType.GetFields(flags);