小编Jre*_*ene的帖子

用类常量值填充 List<string> 的方法。C#

我需要创建一种方法来填充 List<string>使用在自己的类中定义的常量的值。

为您提供类中定义的众多(20总共)const蚂蚁的快速示例:

private const string NAME1 = "NAME1";
private const string NAME2 = "NAME2";
private const string NAME3 = "NAME3";
...
Run Code Online (Sandbox Code Playgroud)

如您所见,常量的名称等于它的值,如果这有帮助的话。

到目前为止,查看我在 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;
}
Run Code Online (Sandbox Code Playgroud)

我作为程序员的经验相当低,就像我使用 C# 的经验一样;我不确定是否type.GetType().GetProperties()引用了常量名称,该property.Name行也会发生同样的情况。

这种方法是否符合我的要求?

c# reflection constants

7
推荐指数
1
解决办法
446
查看次数

标签 统计

c# ×1

constants ×1

reflection ×1