[英]What is a good way to handle enums that need to be strings
我很確定一個枚舉不是我想要的。 我想要的是一個命名項目列表
CustomerLookup = "005",
CustomerUpdate = "1010"
“005”和“1010”不是我的值,它們是我需要發送給我無法控制的第三方的值。 其中有近500個。 我只是希望我的代碼看起來不錯。
代替
SendRequest("005");
我寧願看
SendRequest(RequestType.CustomerLookup);
任何人都有任何自我記錄的想法,而不會在代碼中瘋狂嗎?
有什么不妥:
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
屬性來獲取相關的字符串值。
如何使用某種關聯數組 ?
你已經這樣做的方式似乎對我而言。
您明確地在代碼中定義了請求類型值而沒有含糊之處,當您使用它們時,您就會有智能感知。
我認為真正的問題是如何在沒有任何tyypos的情況下將500個值放入代碼中!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.