0

我有一个关于字符串连接的简单问题。以下是代码。我想问为什么 s6 = "abcde" 而不是 "akcde"?我已将 s2 值更改为“k”。

Public Class Form1
    Public s1 As String = "a"
    Public s2 As String = "b"
    Public s3 As String = "c"
    Public s4 As String = "d"
    Public s5 As String = "e"
    Public s6 As String = ""
    Public s7 As String = "k"

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        s6 = s1 & s2 & s3 & s4 & s5
        s2 = s7
        MessageBox.Show(s6) 's6 = abcde

    End Sub
End Class
4

5 回答 5

1

因为当您将值分配给 s6 - 创建一个基于 s1 - s5 串联的新字符串 - 之后更改 s2 对 s6 中的值没有影响

于 2012-04-12T10:36:12.160 回答
1

当您将值存储在 s6 中时,它会存储为“abcde”,然后在您更改 s2 的值之后,因此 s6 不受影响,因为它不存在于表达式“s2=s7”中

因为编译器只得到 s2 和 s7,所以它的工作原理是,当您更改任何一个变量时,编译器不会检查每个变量.....

于 2012-04-12T11:26:07.793 回答
0

当你这样做时:

s6 = s1 & s2 & s3 & s4 & s5

s6contains abcde,一个由连接产生的新字符串。

然后更改变量的值s2——这不会改变s6

于 2012-04-12T10:38:24.513 回答
0

当连接 2 个字符串时,会生成一个新字符串,因为字符串是不可变的。即使您修改了一个字符串,也会生成一个新的字符串。为了证明这一点,只需尝试

s1 = "foo"
s2 = s1
s1 = s1 + "bar" 's2 == 'foo'

经验法则:不要将字符串变量视为对字符串的引用,而应将其视为值对象,就像 int 或 bool 变量一样。

于 2012-04-12T10:38:39.047 回答
0

你只是在做你的分配并以错误的顺序连接,改变这个;

Public Class Form1
    Public s1 As String = "a"
    Public s2 As String = "b"
    Public s3 As String = "c"
    Public s4 As String = "d"
    Public s5 As String = "e"
    Public s6 As String = ""
    Public s7 As String = "k"

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        s2 = s7
        s6 = s1 & s2 & s3 & s4 & s5
        MessageBox.Show(s6) 's6 = abcde

    End Sub
End Class
于 2012-04-12T10:40:40.263 回答