将通用枚举传递给函数

问题描述 投票:0回答:1

在下面的函数中,我使用 switch 语句来确定需要循环的枚举类型。有没有办法可以将泛型类型的枚举传递给函数以避免 switch 语句?或者我应该使用枚举以外的其他东西来做到这一点?

public static void ShowGroupSub(List<BasicTriListWithSmartObject> panels, uint type,uint sub)
{
    foreach (BasicTriListWithSmartObject panel in panels)
    {
        switch(type)
        {
            case (uint)SubGroups.Control:
                foreach (uint index in Enum.GetValues(typeof(**ControlSubs**)))
                    panel.BooleanInput[index].BoolValue = false;
                panel.BooleanInput[sub].BoolValue = true;
                break;
            case (uint)SubGroups.Presets:
                foreach (uint index in Enum.GetValues(typeof(**PresetSubs**)))
                    panel.BooleanInput[index].BoolValue = false;
                panel.BooleanInput[sub].BoolValue = true;
                break;
            case (uint)SubGroups.VideoCall:
                foreach (uint index in Enum.GetValues(typeof(**VideoCallSubs**)))
                    panel.BooleanInput[index].BoolValue = false;
                panel.BooleanInput[sub].BoolValue = true;
                break;
        }
    }
}

public enum SubGroups : uint
{
    Control      = 1,
    Presets      = 2,
    VideoCall    = 3
}

public enum ControlSubs : uint
{
    Bluray = 60,
    PC = 61,
    Laptop = 62,
    AirMedia = 63,
    ClickShare = 64,
    CamControl = 65,
    DocCam = 66,
    CATV = 67,
}

public enum PresetSubs : uint
{
    Main = 60,
    Edit = 61
}

public enum VideoCallSubs : uint
{
    Contacts = 271,
    Keyboard = 272,
    Camera = 273,
    CallActive = 274,
    AddCallContacts = 275,
    AddCallKeyboard = 276
}

这可行,但看看是否有更好的方法。

c# function enums
1个回答
0
投票

由于

type
不会改变,因此枚举值始终相同,并且可以在循环之前确定。这可以在 switch 表达式中完成,它比 switch 语句更容易编写。

switch case 中的大部分代码是相同的,无需重复。

public static void ShowGroupSub(List<BasicTriListWithSmartObject> panels, uint type, uint sub)
{
    uint[] enumValues = (SubGroups)type switch {
        SubGroups.Control => (uint[])Enum.GetValues(typeof(ControlSubs)),
        SubGroups.Presets => (uint[])Enum.GetValues(typeof(PresetSubs)),
        SubGroups.VideoCall => (uint[])Enum.GetValues(typeof(VideoCallSubs)),
        _ => throw new ArgumentException($"Unknown type {type}", nameof(type))
    };
    foreach (BasicTriListWithSmartObject panel in panels) {
        foreach (uint index in enumValues) {
            panel.BooleanInput[index].BoolValue = false;
        }
        panel.BooleanInput[sub].BoolValue = true;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.