小编C P*_*ton的帖子

是否有更有效的方法通过C#中的switch-case语句运行枚举值而不是这个?

我想知道是否有一个更有效(在更简单/更简洁的代码中有效)的方式来制作如下所示的案例陈述......

我有一本字典.它的关键类型是Enum,它的值类型是bool.如果布尔值为true,我想更改表单上标签的颜色.

为示例更改了变量名称.

Dictionary<String, CustomType> testDict = new Dictionary<String, CustomType>();

//populate testDict here...

Dictionary<MyEnum, bool> enumInfo = testDict[someString].GetEnumInfo(); 
//GetEnumInfo is a function that iterates through a Dictionary<String, CustomType>
//and returns a Dictionary<MyEnum, bool>

            foreach (KeyValuePair<MyEnum, bool> kvp in enumInfo)
            {
                switch (kvp.Key)
                {
                    case MyEnum.Enum1:
                        if (someDictionary[kvp.Key] == true)
                        {
                            Label1.ForeColor = Color.LimeGreen;
                        }
                        else
                        {
                            Label1.ForeColor = Color.Red;
                        }
                        break;
                    case MyEnum.Enum2:
                       if (someDictionary[kvp.Key] == true)
                        {
                            Label2.ForeColor = Color.LimeGreen;
                        }
                        else
                        {
                            Label2.ForeColor = Color.Red;
                        }
                        break;
               } …
Run Code Online (Sandbox Code Playgroud)

c# performance switch-statement

4
推荐指数
1
解决办法
372
查看次数

标签 统计

c# ×1

performance ×1

switch-statement ×1