创建一个基于Guid触发的切换案例

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

我正在处理会触发基于某些guid的开关盒。。

问题是,如果不将guid设置为静态只读,则无法存储它。

我该如何解决此问题?

public struct Types
{
    public static readonly Guid Standard = new Guid("{11111111-1111-1111-1111-111111111111}");
    public static readonly Guid Morning = new Guid("{22222222-2222-2222-2222-222222222222}");
}

public string GetStyle(Guid stage)
{
    switch (stage)
    {
        case Types.Standard:
            return "Not normal";
        case Types.Morning:
            return "Not anormal";
        default:
            return "Normal";
            break;
    }
}
c# static switch-statement const
2个回答
1
投票

使用latest switch syntax (aka "pattern matching"),您可以实现:

        public static string GetStyle(Guid stage)
        {
            switch (stage)
            {
                case Guid standard when standard == new Guid("{11111111-1111-1111-1111-111111111111}"):
                    return "Not normal";
                case Guid morning when morning == new Guid("{22222222-2222-2222-2222-222222222222}"):
                    return "Not anormal";
                default:
                    return "Normal";
            }
        }

1
投票

处理此问题的一种方法是使用Dictionary<Guid, string>将Guid映射到对应的字符串,然后从字典中返回一个值(如果存在)。这完全减少了对switch语句的需要,并且应该可以使代码更简洁。

private Dictionary<Guid, string> StyleMap = new Dictionary<Guid, string>
{
    {Types.Standard, "Not normal" },
    {Types.Morning, "Not anormal" },
};

public string GetStyle(Guid stage)
{
    string result;
    return styleMap.TryGetValue(stage, out result) ? result : "Normal";
}
© www.soinside.com 2019 - 2024. All rights reserved.