迭代静态类的属性来填充列表? [英] Iterate through properties of static class to populate list?

查看:91
本文介绍了迭代静态类的属性来填充列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class of string constants, how can I loop through to get the string and populate a list-box?

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

I can't create a new instance of Fields because its a static class. How can I get all the fields into the list-box without manually inserting each one?

推荐答案

尝试用这样的方式反思:

try Reflection with somethin like this:

(更新版本)

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

这篇关于迭代静态类的属性来填充列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆