加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 循环通过一个类的常量成员

发布时间:2020-12-15 06:33:09 所属栏目:百科 来源:网络整理
导读:我有一个有恒定字符串的类.我想将所有这些字符串都放入一个下拉列表中.这样做最好的方法是什么?这就是我现在所说的,理论上我认为这是最好的办法. public class TestClass{ private const string _testA = "Test A"; private const string _testB = "Test B"
我有一个有恒定字符串的类.我想将所有这些字符串都放入一个下拉列表中.这样做最好的方法是什么?这就是我现在所说的,理论上我认为这是最好的办法.
public class TestClass
{
    private const string _testA = "Test A";
    private const string _testB = "Test B";

    public string TestA
    {
        get { return _testA; }
    }

    public string TestB
    {
        get { return _testB; }
    }
}

public DropDownItemCollection TestCollection
{
    DropDownItemCollection collection = new DropDownItemCollection();
    TestClass class = new TestClass();

    foreach (string testString in class)
    {
        DropDownItem item = new DropDownItem();
        item.Description = testString;
        item.Value = testString;
        collection.Add(item);
    }

    return collection;
}

问题是这会在foreach上返回一个错误:“…不包含GetEnumerator的公共定义”.我试图创建一个GetEnumerator,但我一直没有成功,我以前没有使用过GetEnumerator.

任何帮助是极大的赞赏!

解决方法

您可以使用反射循环遍历所有属性:
public DropDownItemCollection TestCollection
{
    var collection = new DropDownItemCollection();
    var instance = new TestClass();
    foreach (var prop in typeof(TestClass).GetProperties())
    {
        if (prop.CanRead)
        {
            var value = prop.GetValue(instance,null) as string;
            var item = new DropDownItem();
            item.Description = value;
            item.Value = value;
            collection.Add(item);
        }
    }
    return collection;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读