【发布时间】:2016-11-12 01:39:41
【问题描述】:
除了使用如下代码所示的 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;
}
【问题讨论】:
-
你能定义一个数组中的所有常量,然后循环遍历这个数组来检查常量值吗?
-
您可以将所有常量值放在一个 ArrayList 中,在比较特定元素是否等于 foo.Type 时迭代列表。
-
这可能会帮助stackoverflow.com/questions/14971631/…,然后只需执行 IndexOf(foo.Type)