如何循环遍历静态常量类?

9

除了在下面的代码中使用Switch语句之外,还有其他的方法可以检查foo.Type是否与Parent.Child类中的任何常量匹配吗?

目标是循环遍历所有常量值,以查看foo.Type是否匹配,而不必指定每个常量作为case

父类:

public class Parent
{
    public static class Child
    {
        public const string JOHN = "John";
        public const string MARY = "Mary";
        public const string JANE = "Jane";
    }
}

代码:

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

你能否定义一个包含所有常量的数组,并透过循环来检查常量的值? - Peter
你可以将所有的常量值放入一个ArrayList中,遍历列表并比较特定元素是否等于foo.Type。 - HaroldSer
尝试参考这个链接:https://dev59.com/lWUp5IYBdhLWcg3w5Kk6,然后使用 **IndexOf(foo.Type)**。 - Jeremy Thompson
3个回答

9

使用Reflection,您可以找到类中的所有常量值:

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

然后你可以检查值是否包含某些内容:
if(values.Contains("something")) {/**/}

1
虽然你可以使用反射循环遍历像这样声明的常量(正如其他答案所示),但这并不理想。
将它们存储在某种可枚举对象中会更加高效:数组、List、ArrayList,无论哪种最适合您的要求。
例如:
public class Parent {
    public static List<string> Children = new List<string> {"John", "Mary", "Jane"}
}

然后:

if (Parent.Children.Contains(foo.Type) {
    //do something
}

0
你可以使用反射来获取给定类的所有常量:
var type = typeof(Parent.Child);
FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public |
BindingFlags.Static | BindingFlags.FlattenHierarchy);

var constants = fieldInfos.Where(f => f.IsLiteral && !f.IsInitOnly).ToList();
var constValue = Console.ReadLine();
var match = constants.FirstOrDefault(c => (string)c.GetRawConstantValue().ToString() == constValue.ToString());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接