且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过类的成员不断循环

更新时间:2023-10-12 23:45:22

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

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