c# - 遍历静态类的属性来填充列表?

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

最佳答案

像这样尝试反射:

(更新版本)

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

关于c# - 遍历静态类的属性来填充列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12480279/

相关文章:

c - 嵌入式系统 C 重启后的静态重新定义

java - 如何制作迭代方法的递归版本?

jquery - 对表元素的重复 ajax 请求

c# - 从 Base64 字符串创建图像时 GDI+ 中出现一般错误

c# - 如何正确绑定(bind)MVVM中的Image.Source?

c# - 如何为泛型类命名 C# 源文件

c# - 执行后处置ReactiveCommand

同一应用程序池中不同 Web 应用程序中的 c# 静态变量

c# - 静态类的静态方法与非静态类的静态方法 (C#)

bash - 如何在 bash 中的变量中容纳空格并在 linux 中的目录树中迭代