如何遍历静态类常量?

Wel*_*ing 6 c# asp.net loops

而不是使用如下代码中所示的Switch语句,是否有另一种方法来检查是否foo.Type与类中的任何常量匹配Parent.Child

预期的目标是遍历所有常量值以查看是否foo.Type匹配,而不是必须将每个常量指定为a case.

家长班:

public class Parent
{
    public static class Child
    {
        public const string JOHN = "John";
        public const string MARY = "Mary";
        public const string JANE = "Jane";
    }
}
Run Code Online (Sandbox Code Playgroud)

码:

switch (foo.Type)
{
     case Parent.Child.JOHN:
     case Parent.Child.MARY:
     case Parent.Child.JANE:
         // Do Something
         break;
}
Run Code Online (Sandbox Code Playgroud)

Rez*_*aei 5

使用反射,您可以在类中找到所有常量值:

var values = typeof(Parent.Child).GetFields(BindingFlags.Static | BindingFlags.Public)
                                 .Where(x => x.IsLiteral && !x.IsInitOnly)
                                 .Select(x => x.GetValue(null)).Cast<string>();
Run Code Online (Sandbox Code Playgroud)

然后,您可以检查值是否包含某些内容:

if(values.Contains("something")) {/**/}
Run Code Online (Sandbox Code Playgroud)