是否可以枚举对象中的公共静态字符串?

Mic*_*hel 2 c#

在这段代码中,他们使用了这种结构而不是枚举:

包含所有公共静态字符串的公共类.

是否可以枚举类中的静态字符串?

mgr*_*ber 6

这将枚举类中公共静态字段的字符串值MyClass:

var flags = BindingFlags.Public | BindingFlags.Static;
var query = typeof(MyClass)
        .GetFields(flags)
        .Where(fieldInfo => fieldInfo.FieldType == typeof(string))
        .Select(fieldInfo => fieldInfo.GetValue(null));
foreach (var value in query) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

对于公共静态属性,它几乎是相同的:

var flags = BindingFlags.Public | BindingFlags.Static;
var query = typeof(MyClass)
        .GetProperties(flags)
        .Where(propertyInfo => propertyInfo.PropertyType == typeof(string))
        .Select(propertyInfo => propertyInfo.GetValue(null, null));
foreach (var value in query) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)