2012-09-18 71 views
11

我有一個字符串常量的類,我怎麼可以循環獲取字符串和填充列表框?迭代靜態類的屬性來填充列表?

static class Fields 
{ 
    static readonly string FirstName = "FirstName"; 
    static readonly string LastName = "LastName"; 
    static readonly string Grade = "Grade"; 
    static readonly string StudentID1 = "StudentID"; 
    static readonly string StudentID2 = "SASINumber"; 
} 

public partial class SchoolSelect : Form 
{ 
    public SchoolSelect() 
    { 
     InitializeComponent(); 

     //SNIP 

     // populate fields 
     //Fields myFields = new Fields(); // <-- Cant do this 
     i = 0; 
     foreach (string field in Fields) // ??? 
     { 
      fieldsBox.Items.Insert(i, Fields ??? 
     } 
    } 

我無法創建一個新的Fields實例,因爲它的靜態類。如何在不手動插入每個字段的情況下將所有字段放入列表框?

回答

17

嘗試與思考這樣的事端:

(更新版)

 Type type = typeof(Fields); // MyClass is static class with static properties 
     foreach (var p in type.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)) 
     { 
      var v = p.GetValue(null); // static classes cannot be instanced, so use null... 
      //do something with v 
      Console.WriteLine(v.ToString()); 
     } 
+3

因爲你正在尋找的字段(的問題),而不是性能,你應該使用type.GetFields(),和甚至可以添加一個BindingFlag作爲方法的參數,比如BindingFlags.Static(不知道確切的名字) –

+0

@Chery:Aaahh .... + 1 – Cybermaxs

+0

現在工作,謝謝! – pdizz