【问题标题】:Make an switch case that triggers based on Guid制作一个基于 Guid 触发的 switch case
【发布时间】:2019-09-28 19:29:09
【问题描述】:

我正在研究一个基于某些 guid 触发的 switch case。

问题是如果不将其设置为静态只读,我就无法存储 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;
    }
}

【问题讨论】:

  • switch 不适用于Guid,因此如果您在谈论static readonlyconst,您将无能为力。您真的需要使用开关吗?
  • @madreflection 现在只需要调整两种情况,但这很容易增长,因此我决定使用开关,因为它可以轻松扩展
  • @RufusL fixed... :D 我的错误是尝试制作最小版本,复制粘贴错误

标签: c# static switch-statement constants


【解决方案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";
            }
        }

【讨论】:

  • 您可以按照自己喜欢的方式进行润色或重新格式化。如果能解决您的问题,请标记为答案。
【解决方案2】:

处理此问题的一种方法是使用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";
}

【讨论】:

  • 这看起来很干净,但也需要在每次有人调用 GetStyle 函数时创建字典...
  • return styleMap.TryGetValue(stage, out var result) ? result : "Normal"; 仅当字典可以更改时才真正需要,但我相信它可以避免第二次搜索,无论它有什么价值。
  • @ane 是的。我在答案中有对此的评论,但我想不出一个很好的理由 not 将它作为一个字段,所以我相应地修改了答案。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多