gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:42:59 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com