循环通过类的常量成员

我有一个包含常量字符串的类。 我想将所有这些字符串放入下拉集合中。 做这个的最好方式是什么? 这就是我现在所拥有的,理论上,我认为这将是最好的方法。

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。

任何帮助是极大的赞赏!

您可以使用reflection遍历所有属性:

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

有点晚了,但这不是一个更好的解决方案吗?

http://weblogs.asp.net/whaggard/archive/2003/02/20/2708.aspx

 private FieldInfo[] GetConstants(System.Type type) { ArrayList constants = new ArrayList(); FieldInfo[] fieldInfos = type.GetFields( // Gets all public and static fields BindingFlags.Public | BindingFlags.Static | // This tells it to get the fields from all base types as well BindingFlags.FlattenHierarchy); // Go through the list and only pick out the constants foreach(FieldInfo fi in fieldInfos) // IsLiteral determines if its value is written at // compile time and not changeable // IsInitOnly determine if the field can be set // in the body of the constructor // for C# a field which is readonly keyword would have both true // but a const field would have only IsLiteral equal to true if(fi.IsLiteral && !fi.IsInitOnly) constants.Add(fi); // Return an array of FieldInfos return (FieldInfo[])constants.ToArray(typeof(FieldInfo)); } 

如果你需要你可以做的名字

 fi.GetValue(null) 

在循环内。

您可以实现一个产生字符串的方法:

 public Ienumerable GetStrings(){ yield return _TestA; yield return _TestB; } 

否则,您应该查看reflection以返回静态和字符串的属性,然后通过调用它们来获取值。

关心GJ

您可以使用reflection来循环使用类属性:

 var instance = new TestClass(); foreach(PropertyInfo pi in typeof(TestClass)) { var val = pi.GetValue(instance,null); } 

我刚刚遇到了同样的挑战; 获取我的类的所有常量(不是属性!)。 基于最受欢迎的答案(对于属性)和John的答案(对于常量)我写了这个。 我测试了它,效果很好。

 private List lstOfConstants= new List(); foreach (var constant in typeof(TestClass).GetFields()) { if (constant.IsLiteral && !constant.IsInitOnly) { lstOfConstants.Add((string)constant.GetValue(null)); } } 

您需要使用reflection从您的自定义类型获取每个String的名称,然后还/可选地获取每个字符串的值…

像这样的东西:

 TestClass theClass = new TestClass(); foreach (PropertyInfo property in theClass.GetType().GetProperties()) { Console.WriteLine(property.Name); Console.WriteLine(property.GetValue(theClass, null)); }