通过类的成员不断循环 [英] Loop through constant members of a class

查看:78
本文介绍了通过类的成员不断循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有它的常量字符串类。我想所有这些串扔进一个下拉集合。什么是做到这一点的最好方法是什么?这就是我现在在理论上,我认为这将是做到这一点的最好办法。

I have a class with constant strings in it. I'd like to throw all of those strings into a drop down collection. What is the best way to do this? This is what I have now and in theory, I would think that it would be the best way to do this.

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的工作。

The problem is that this returns an error on the foreach: "...does not contain a public definition for GetEnumerator." I've tried to create a GetEnumerator but I've been unsuccessful and I haven't worked with GetEnumerator in the past.

任何帮助是非常感谢!

推荐答案

您可以通过所有属性使用反射来循环:

You could use reflection to loop through all the properties:

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

这篇关于通过类的成员不断循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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