Private Const TOKEN_LENGTH As Integer = 8 ' this may come from app.config at startup
Private Const TOKEN_MIN As Integer = 10 ^ (TOKEN_LENGTH - 1)
Private Const TOKEN_MAX As Integer = 10 ^ TOKEN_LENGTH - 1
'how do I make TOKEN_FORMAT a CONST?
Private Const TOKEN_FORMAT As String = "0".PadRight(TOKEN_LENGTH)
'sample usage
Dim TokenCode As String = New Random().Next(TOKEN_MIN, TOKEN_MAX).ToString(TOKEN_FORMAT)
以下代码给出了此错误:需要常量表达式。
Private Const TOKEN_FORMAT As String = "0".PadRight(TOKEN_LENGTH)
一旦定义,TOKEN_FORMAT将永远不会改变,其定义仅取决于另一个常数TOKEN_LENGTH。那么为什么它也不能被编译时评估呢?
感谢。
答案 0 :(得分:1)
你想要太花哨了。这些是常量,因此给它们保持不变的值。你的TOKEN_LENGTH
常数毫无意义。
Const TOKEN_FORMAT As String = "00000000"
Const TOKEN_MIN As Integer = 10000000
Const TOKEN_MAX As Integer = 99999999
这就是你所需要的一切。
答案 1 :(得分:0)
你需要什么方式更好?没有setter的财产怎么样,例如:
Public Class ConstantTest
Private Const TOKEN_LENGTH As Integer = 6
Private ReadOnly Property TOKEN_FORMAT() As String
Get
Return "0".PadRight(TOKEN_LENGTH, "0"c)
End Get
End Property
Private ReadOnly ANOTHER_TOKEN_FORMAT As String = "0".PadRight(TOKEN_LENGTH, "0"c)
Public Sub New()
'you can change readonly field in constructor...'
ANOTHER_TOKEN_FORMAT = "test"
'but setting "get-only" property is not allowed even in constructor'
TOKEN_FORMAT = "test" '<- compile error here'
End Sub
End Class
您可以在构造函数中更改readonly字段的值,使其与Const
不太相似,但是相同的技巧不能应用于没有setter的属性,如上例所示。
相关讨论:const vs. readonly,What is the difference between const and readonly?