迭代静态类的属性来填充列表?

时间:2012-09-18 15:34:28

标签: c# static iteration

我有一类字符串常量,如何循环获取字符串并填充列表框?

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实例,因为它是一个静态类。如何在不手动插入每个字段的情况下将所有字段放入列表框?

1 个答案:

答案 0 :(得分:27)

尝试用这样的东西反思:

(更新版本)

        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());
        }