代码之家  ›  专栏  ›  技术社区  ›  Matt Dawdy

处理需要字符串的枚举的好方法是什么

  •  2
  • Matt Dawdy  · 技术社区  · 15 年前

    我很确定枚举不是我想要的。我想要的是一个命名项目的列表

    CustomerLookup = "005",
    CustomerUpdate = "1010"
    

    而不是

    SendRequest("005");
    

    我宁愿去看看

    SendRequest(RequestType.CustomerLookup);
    

    有没有人有任何自我记录的想法,而不是疯狂的代码?

    3 回复  |  直到 15 年前
        1
  •  8
  •   Jon Skeet    15 年前

    有什么问题吗:

    public static class RequestType
    {
         public static readonly string CustomerLookup = "005";
         // etc
    }
    

    public static class RequestType
    {
         public const string CustomerLookup = "005";
         // etc
    }
    

    public sealed class RequestType
    {
         public static readonly RequestType CustomerLookup = new RequestType("005");
         // etc
    
         public string Code { get; private set; }
    
         private RequestType(string code)
         {
             this.Code = code;
         }
    }
    

    这将基本上为您提供一组固定的值(构造函数是私有的,因此外部代码不能创建不同的实例),并且您可以使用 Code 属性获取相关字符串值。

        2
  •  0
  •   Community Mohan Dere    9 年前
        3
  •  0
  •   CResults    15 年前

    你现在的做法在我看来是对的。

    我认为真正的问题是如何在没有任何typos的情况下将500个值放入代码中!