来自类中变量字段的GetValue()

时间:2015-04-19 20:16:02

标签: c# fieldinfo

假设我有一个简单的类:

 public class TestScript : MonoBehaviour {
      public Vector3 myVector3;
 }

现在我想迭代这个类的一个实例的字段并访问该字段的字段(Field-Ception!)并将值分配给正确类型的变量,有效地"包装&# 34;该字段因此可以序列化。在这里,我将到达Vector3字段" myVector3"到达它之后,浏览它的字段并将它们的值分配给三个浮点数(Vector3由它组成)。

问题? fieldinfo。GetValue()返回类型MonoField!如果我使用fieldinfo。FieldType,它会返回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.
                }
           }
      }
 }

1 个答案:

答案 0 :(得分:1)

在这种情况下,

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

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