2010-11-28 57 views
3

我有一個類有很多公共變量,我需要能夠得到它們的列表。如何獲得我在一個類中擁有的所有公共變量的列表? (C#)

這裏是我的類的例子:

public class FeatList: MonoBehaviour { 
public static Feat Acrobatic = new Feat("Acrobatic", false, ""); 
public static Feat AgileManeuvers = new Feat("Agile Maneuvers", false, ""); void Start(){}} 

除了有大約100多個變量。有沒有任何可能的方法來獲得所有這些成員變量在一個可管理的數組?還是我把自己搞砸了?

回答

0

這將返回壯舉類型的所有公共字段的字段信息數組:

var fields = typeof(Feat).GetFields(); 

然後,你可以這樣寫/寫字段:

var field1 = fields[0]; 
var field1value = field1.GetValue(Acrobatic); 

五言中,GetValue返回類型化的對象,所以你需要將它按需轉換爲正確的類型。

+0

你需要指定一個`BindingFlag`。 – 2010-11-28 06:03:15

+0

不,我不知道。默認情況下,包括靜態,公共和實例字段。 – 2010-11-29 16:46:26

1

如果「變量」你的意思是類字段(如類級別的變量),你可以使用FieldInfo class (see MSDN link for more info)

using System; 
using System.Reflection; 

public class FieldInfoClass 
{ 
    public int myField1 = 0; 
    protected string myField2 = null; 
    public static void Main() 
    { 
     FieldInfo[] myFieldInfo; 
     Type myType = typeof(FieldInfoClass); 
     // Get the type and fields of FieldInfoClass. 
     myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance 
      | BindingFlags.Public); 
     Console.WriteLine("\nThe fields of " + 
      "FieldInfoClass are \n"); 
     // Display the field information of FieldInfoClass. 
     for(int i = 0; i < myFieldInfo.Length; i++) 
     { 
      Console.WriteLine("\nName   : {0}", myFieldInfo[i].Name); 
      Console.WriteLine("Declaring Type : {0}", myFieldInfo[i].DeclaringType); 
      Console.WriteLine("IsPublic  : {0}", myFieldInfo[i].IsPublic); 
      Console.WriteLine("MemberType  : {0}", myFieldInfo[i].MemberType); 
      Console.WriteLine("FieldType  : {0}", myFieldInfo[i].FieldType); 
      Console.WriteLine("IsFamily  : {0}", myFieldInfo[i].IsFamily); 
     } 
    } 
} 

取而代之的查詢在這個MSDN微軟例如使用反射獲得接入,如本例中的FieldInfoClass從Main方法中可以選擇你的FeatList類。邏輯不需要在同一個類的主要方法中。你可以將你的邏輯版本放到你想要查詢的實體的外部,並且實際上用這種邏輯來查詢任何對象或類。

無論這些字段是私人的還是公共的還是別的什麼都沒關係 - 通過反射您可以訪問所有這些字段。

有關如何使用反射提取字段值的信息,請參閱MSDN示例代碼FieldInfo.GetValue(..) method (MSDN link)

+0

有什麼方法可以使用變量嗎?我需要調用它們的方法。如果(FeatExample.boolThing){//代碼} – UnityPrgmer 2010-11-28 06:48:44

1

,如果你是varaible 名稱後面 - 那麼這將給予他們給你:

IEnumerable<string> variableNames = 
    typeof(FeatList).GetFields(BindingFlags.Instance | 
      BindingFlags.Static | BindingFlags.Public) 
     .Select(f => f.Name); 

,但如果你想VALUES,那麼這將工作:

Dictionary<string,object> variableValues = 
    typeof (FeatList).GetFields(BindingFlags.Instance | 
      BindingFlags.Static | BindingFlags.Public) 
     .ToDictionary(f => f.Name, f => f.GetValue(myFeatList)); 
相關問題