繁体   English   中英

如何遍历静态类常量?

[英]How to loop through a static class of constants?

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

预期目标是遍历所有常量值以查看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;
}

您可以在类中找到所有常量值:

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")) {/**/}

虽然你可以循环使用反射声明的常量(如其他答案所示),但它并不理想。

将它们存储在某种可枚举的对象中会更有效:数组,List,ArrayList,最适合您的要求。

就像是:

public class Parent {
    public static List<string> Children = new List<string> {"John", "Mary", "Jane"}
}

然后:

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

您可以使用反射来获取给定类的所有常量:

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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM