25

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

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

4

1 回答 1

49

用这样的东西尝试反射:

(更新后的版本)

        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());
        }
于 2012-09-18T15:37:09.457 回答