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
Next
return i.ToString()
End Function
我想保留i的值,但是一旦它返回到MethodOne,它就会失去它的价值。我尝试制作static i As integer = 0
,但这不起作用。
答案 0 :(得分:1)
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
答案 1 :(得分:0)
考虑这个与你的有点不同的例子(向i添加5而不是设置值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
现在,在第一次运行时,我将被设置为静态值,它将为0.它将增加5,因此值将为5.在第二次运行时,i的值仍为5,并且它将增加5.新值将为10.
在您的示例中,我始终设置为5,因此如果您保留了值,则不会更改任何内容。
问题更改后修改:
你想要做的是拥有一个类成员,而不是一个方法变量。如果方法运行后该值仍为0,则有两个可能的原因。之一:
您可以通过断点调试了解正在发生的事情。