通过不同的 class 从 class 寻址一个 int[] 数组并且也是从字符串构造的?

Address an int[] array from a class through a different class and is also constructed from a string?

重要的一点是使用字符串构造引用。即,我需要从字符串的构造中访问那个 int[]。

例如使用 "myClass ["int"+myString]" 访问 myClass.intArray

我做错了什么?我该怎么做?

 using UnityEngine;
 using System;
 using System.Collections;
 using System.Collections.Generic;

 public class MyClass : MonoBehaviour {

 public int[] intArray = new int[3]{1,2,3};
 }

 //---------------------------------------------------------------------------

 using UnityEngine;
 using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.Reflection;

 public class MyOtherClass : MonoBehaviour {
     MyClass myClass;

     void theMethod(string myString){
          myClass = GetComponent<MyClass> ();

//-->错误在这里://

          int[] theArray = myClass.GetType ().GetFields (myClass ["int"+myString]);

//--//

          theArray[0] = 4;
     }

     void Awake(){ theMethod("Array"); }
 }

方法GetFields returns multiple fieldinfo's. GetField returns one informational class for one field.

使用此 FieldInfo,您可以从您的实例中检索实际值(如您所说:地址)。检索后,您可以使用它的值:

FieldInfo fi = myClass.GetType().GetField("int"+myString); // GetField instead of GetFields.
int[] theArray = (int[])fi.GetValue(myClass);
theArray[0] = 4;
myClass.GetType ().GetFields ();

returns an Array of FieldInfo-对象。

所以你可以那样做:

var fieldInfo = myClass.GetType().GetFields().Where(f=>f.Name == "int" + myString).First();

然后像这样访问它的值:

var theArray = fieldInfo.GetValue(myClass) as int[];
theArray[0] = 4;

要省略 Linq-Part,您还可以使用 GetField 方法(这可能是您首先尝试的方法)

var fieldInfo = myClass.GetType().GetField("int" + myString);  // returns single FieldInfo for your field

另请注意,由于这不是 JavaScript,您无法像在 GetFields(myClass["int" + myString]);

中尝试的那样使用索引运算符访问您的字段