我需要创建一个方法,使我能够填充 List<string>
,并将其中的值设为类中定义的常量。
这是一个例子,该类中定义了许多常量(一共有 20
个):
private const string NAME1 = "NAME1";
private const string NAME2 = "NAME2";
private const string NAME3 = "NAME3";
...
正如您所见,常量的名称等于其值,如果有帮助的话。
到目前为止,我在StackOverflow上找到了各种类型解决类似问题的示例,我得出了以下结论:
public static List<string> GetConstantNames()
{
List<string> names = new List<string>();
Type type = typeof(ClassName);
foreach (PropertyInfo property in type.GetType().GetProperties())
{
names.Add(property.Name);
}
return names;
}
我的编程经验很少,对C#的经验也不多。 我不确定
type.GetType().GetProperties()
是否引用常量名称,
property.Name
行也是如此。
这个方法是否能够完成我所要求的功能?
GetConstantNames()
方法时,想要获得一个包含在顶部定义的常量值的List,类似于List<string> names = "NAME1","NAME2","NAME3",...
。 - Jrene