简体   繁体   English

如何遍历静态类常量?

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

Instead of using a Switch statement as shown in the code below, is there an alternative way to check if foo.Type is a match to any of the constants in the Parent.Child class? 有没有一种方法来检查foo.Type是否与Parent.Child类中的任何常量匹配,而不是使用下面代码中显示的Switch语句?

The intended goal is to loop through all of the constant values to see if foo.Type is a match, rather than having to specify each constant as a case . 预期目标是遍历所有常量值以查看foo.Type是否匹配,而不是必须将每个常量指定为case

Parent Class: 家长班:

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

Code: 码:

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

You can find all constant values in the class: 您可以在类中找到所有常量值:

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

Then you can check if values contains something: 然后你可以检查值是否包含某些内容:

if(values.Contains("something")) {/**/}

While you can loop through constants that are declared like that using reflection (as the other answers show), it's not ideal. 虽然你可以循环使用反射声明的常量(如其他答案所示),但它并不理想。

It would be much more efficient to store them in some kind of enumerable object: an array, List, ArrayList, whatever fits your requirements best. 将它们存储在某种可枚举的对象中会更有效:数组,List,ArrayList,最适合您的要求。

Something like: 就像是:

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

Then: 然后:

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

You can use reflection to get all constants of given class: 您可以使用反射来获取给定类的所有常量:

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