如何在类中的方法中更改Reference传递的参数的值?
即:
Public Class Setting
Public Sub New(Optional ByRef target as String = Nothing)
_target = target
End Sub
Private Sub Go()
If Not IsNothing(_target) Then
_target = "New Value"
End If
End Sub
End Class
用法:
Dim var1 as String = "Old Value"
Dim s as New Setting(var1)
s.Go()
在s.Go()之后,我期待得到:
var1 = "New Value"
但我得到了:
var1 = "Old Value"
由于
答案 0 :(得分:1)
使用包装类
例如,我使用StringBuilder作为包装类。
Public Class Setting
Dim _target As StringBuilder
Public Sub New(Optional ByRef target as StringBuilder = Nothing)
_target = target
End Sub
Private Sub ChangeValue()
If Not IsNothing(_target) Then
_target.Clear()
_target.Append("New Value")
End If
End Sub
Public Sub Go()
ChangeValue()
End Sub
End Class
Sub Main()
Dim var1 as New StringBuilder("Old Value")
Dim s as New Setting(var1)
s.Go()
Console.WriteLine(var1)
End Sub
答案 1 :(得分:0)
这个怎么样......
Public Sub New(Optional ByRef target as String = "")
_target = target
End Sub
Private Sub ChangeValue()
If _target.Length = 0 Then
_target = "New Value"
End If
End Sub
答案 2 :(得分:0)
非常确定它必须像Mike C在评论
中所说的那样使字符串不可变Strings (C# Programming Guide)
字符串对象是不可变的:它们具有后无法更改 已创建。出现的所有String方法和C#运算符 修改字符串实际上会在新的字符串对象中返回结果。
使用Integer进行测试不是苹果,因为Integer是一种值类型
我怀疑=做了很深的复印件
这是C#
即使这样也不会将_s附加到s
public class Sclass
{
public Sclass(ref string s)
{
s += "Sclass";
string _s = s;
_s += "_s";
}
}