2013-07-18 19 views
1

我想要一個wau像enum一樣組織和分組字符串。這是在代碼和值中使用的名稱。由於枚舉只能以積分來創建的,我通常是這樣的:在VB.NET中構建/分組字符串常量的最佳實踐?

**Public Structure SomeStrings 
    Public Shared ReadOnly Property Something1 As String 
     Get 
       Return "Something1"    
     End Get 
    End Property 
    Public Shared ReadOnly Property Something2 As Color 
     Get 
      Return "Something2" 
     End Get 
    End Property 
End Structure** 

有沒有更好的辦法做到這一點?

+0

你就不能使用枚舉的'的ToString()'? – millimoose

+0

VB.NET也有'Consts',您也可以使用靜態只讀*字段*(而不是屬性)。 – millimoose

+0

你有沒有考慮過使用[String Resource files](http://visualbasic.about.com/od/usingvbnet/a/netres090117.htm)? – DaveShaw

回答

4

有沒有更好的方法?

是的,使用Shared ReadOnly字段而不是屬性。你甚至可以通過使用無證XML文檔標籤獲得適當的IDE自動完成像真正的枚舉:

''' <completionlist cref="SomeStrings"/> 
Public Structure SomeStrings 
    Public Shared ReadOnly Something1 As String = "Something1" 
    ' etc. 
End Structure 

有關詳細信息,refer to my previous answer explaining this feature

+0

你能像這樣分組字符串嗎?例如在這樣的代碼中使用:SomeStrings.Something1?還是僅僅將公共共享ReadOnly語句保存在像我的方法中的結構中? – SuppaiKamo

+0

我從來不知道''。這是一個總的遊戲轉換器! –

+0

@Konrad:我的不好,在代碼中沒有看到「結構」,完美地工作! – SuppaiKamo

0

您可能想要考慮創建resources

另一種選擇可能是使用字典。

Dim d As New Dictionary(Of Integer, String) 

d.Add(1, "String 1") 
d.Add(2, "String 2") 

Console.WriteLine(d(2))