Jre*_*ene 7 c# reflection constants
我需要创建一种方法来填充 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行也会发生同样的情况。
这种方法是否符合我的要求?
Dmi*_*nko 11
为了获得consts,您应该使用fields而不是properties 进行操作:
using System.Linq;
using System.Reflection;
...
public static List<string> GetConstantNames() {
return typeof(ClassName)
.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
.Where(fi => fi.IsLiteral && !fi.IsInitOnly) // constants, not readonly
.Where(fi => fi.FieldType == typeof(string)) // of type string
.Select(fi => fi.Name)
.ToList();
}
Run Code Online (Sandbox Code Playgroud)
如果你想获得这两个 const名称和值:
public static Dictionary<string, string> GetConstantNamesAndValues() {
return typeof(ClassName)
.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
.Where(fi => fi.IsLiteral && !fi.IsInitOnly) // constants, not readonly
.Where(fi => fi.FieldType == typeof(string)) // of type string
.ToDictionary(fi => fi.Name, fi => fi.GetValue(null) as String);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
446 次 |
| 最近记录: |