gpt4 book ai didi

c# - 遍历类的常量成员

转载 作者:可可西里 更新时间:2023-11-01 08:31:26 24 4
gpt4 key购买 nike

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

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 的公共(public)定义。”我曾尝试创建 GetEnumerator,但没有成功,而且我过去没有使用过 GetEnumerator。

非常感谢任何帮助!

最佳答案

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

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)

在循环中。

关于c# - 遍历类的常量成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4994469/

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