簡體   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