将文字转换为常量



我是学习Visual Basic的新程序员
现在,我正在做一个关于垒球记分牌的项目。我只使用过文字,所以我没有意识到我的老师想要常量

但我很困惑,因为我真的不确定2之间的区别,也不确定如何将文字转换为常量

如果你能帮忙,我将不胜感激。非常感谢。

Public Class frmSoftballScoreboard
'Declaring array
Dim scores(7) As Double
'declaring variables
Dim runs As String
Dim runningScore As Integer = 0
Dim i As Integer = 0
Dim out As Double
'page load event
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstScores.Items.Add("Runs Running Score")
End Sub
'Enter score button
Private Sub btnScore_Click(sender As Object, e As EventArgs) Handles btnScore.Click
If i < 7 Then
'display inputbox to the user
runs = InputBox("Enter score for " & (i + 1) & " innings", "Score")
'if runs is entered
If runs <> "" Then
'parse the value of runs
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
Else
'display error message
MessageBox.Show("Enter valid runs value")
lblTotal.Text = ""
End If
Else
'if runs is empty then display error message
MessageBox.Show("Enter runs for " & i & "innings")
End If
Else
MessageBox.Show("Only sever innings are allowed")
End If
'calculate total runs And display on the lable
lblTotal.Text = String.Format("final score is {0}", scores.Sum())
End Sub
'Clear Menu click
Private Sub ClearToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles mnuClear.Click
lstScores.Items.Clear()
lblTotal.Text = ""
'reset i to 0
i = 0
End Sub
'Exit Menu click
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles mnuExit.Click
'close application
Application.Exit()
End Sub
End Class

以下是如何做到这一点的示例。

带文字的旧代码:

MessageBox.Show("All well done!")

使用常量编码:

Const SUCCESS_MESSAGE As String = "All well done!"
MessageBox.Show(SUCCESS_MESSAGE)

常量中有占位符的示例:

Const REPLACE_MESSAGE_SAMPLE As String = "This is Number #!"
Dim i As Integer
i = 123
MessageBox.Show(REPLACE_MESSAGE_SAMPLE.Replace("#", i))

您可以使用任何您喜欢的字符串,而不是#。这只是一个样本。

BTW:你的代码看起来像VB.NET而不是VBA。我编辑了它。

您应该使用带占位符的常量:

Const WARNING_MESSAGE$ = "The player {0} must be ready at {1}"
MsgBox(String.Format(WARNING_MESSAGE, "John Davis", #12/11/2018#))

最新更新