Maintain local variable value between calls in vb.net
Public Function MethodOne(ByVal s As String) As String
Dim sb As New StringBuilder()
sb.Append(s)
sb.Append(MethodTwo())
return sb.ToString()
End Function
Public Function MethodTwo() As String
Dim i As Integer = 0
For index As Integer = 0 To 5
i = index
Ne开发者_如何学运维xt
return i.ToString()
End Function
I want to retain the value of i, but once it goes back into MethodOne, it loses its value. I tried making it static i As integer = 0
, but this did not work.
sorry misread that. How about creating a property called Count, and update it whenever MethodTwo is called. You can use the Property Count in MethodTwo instead of i.
Public Function MethodOne(ByVal s As String) As String
Dim sb As New StringBuilder()
sb.Append(s)
sb.Append(MethodTwo())
return sb.ToString()
End Function
Public Property Count As Integer
'Count will be zero when initialized
Public Function MethodTwo() As String
'Dim i As Integer = 0
For index As Integer = 0 To 5
Count = Count + index
Next
return Count.ToString()
End Function
Consider this example which is a bit different than yours (adds 5 to i instead of setting a value of 5)
Public Function MethodOne(ByVal s As String) As String
Dim sb As New StringBuilder()
sb.Append(s)
sb.Append(MethodTwo())
return sb.ToString()
End Function
Public Function MethodTwo() As String
Static i As Integer = 0
i+=5
return i.ToString()
End Function
Now, on the first run i will be set to its static value, which is 0. It will be incremented by 5, so the value will be 5. On the second one, the value of i is still 5, and it will be incremented by 5. The new value will be 10.
In your example, i was always set to 5, so it didn't change anything if you retained the value or not.
Edit after question changed:
What you want to do is have a class member, not a method variable. If the value is still 0 once the method has run, then there are two possible reasons for this. Either:
- The variable is never set (AgeQualifyingCode is never 8 or 10)
- The variable is set to 0 inside the method.
You can find out what is happening with some debugging with breakpoints.
精彩评论