Меня не устраивает то, что tryparse требует от вас заранее объявить выходную переменную, поскольку область действия этой переменной слишком широка. Есть ли лучший способ справиться с этими ситуациями?
Первый пример:
Dim tempDate As Date
If Date.TryParse(TextBox08.Text, tempDate) Then
MonthCalendar1.SetDate(tempDate)
End If
' This code is just a part of a larger function.
' I don't need to use the tempDate in the block where it is declared.
' I only need it inside the if statement and if block.
Второй пример:
If Date.TryParse(TextBox08.Text, Nothing) Then
MonthCalendar1.SetDate(Date.Parse(TextBox08.Text))
End If
' Now I'm parsing the textbox twice . . .
Третий пример:
If Date.TryParse(TextBox08.Text, tempDate) Then
Dim tempDate As Date
MonthCalendar1.SetDate(tempDate)
End If
' Or
If Date.TryParse(TextBox08.Text, Dim tempDate As Date) Then
MonthCalendar1.SetDate(tempDate)
End If
' These would be ideal, but of course they don't compile.
Я копаю слишком глубоко здесь? Может быть, компилятор сам решает эту проблему? Я просто чувствую, что пишу неэффективный код в любом случае, я решу справиться с этим.
Редактировать 1:
Если бы я адаптировал предложение jh00ker к моей ситуации, мой код выглядел бы так:
Private Sub TextBox08_GotFocus(sender As Object, e As EventArgs) Handles TextBox08.GotFocus
'Some Code
Call SetMonthCalendar()
'More Code
End Sub
Private Sub SetMonthCalendar()
Dim tempDate As Date
If Date.TryParse(TextBox08.Text, tempDate) Then
MonthCalendar1.SetDate(tempDate)
End If
End Sub
Это кажется разумным? Он выполняет то, что я хотел, но почти кажется, что решение сложнее, чем проблема.