如何在vb中的文本中间插入变量

时间:2016-01-11 06:14:28

标签: vb.net

例如,如何将变量插入要写入文本文件的文本中?

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim message1 As String = TextBox1.Text
        My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt", "how many edges does" message1 "have?"  , True)
        Process.Start("C:\TestFolder1\test.txt")
    End Sub
End Class

2 个答案:

答案 0 :(得分:3)

我建议改用String.Format。它更具可读性。

请参阅此链接:https://msdn.microsoft.com/pl-pl/library/system.string.format(v=vs.110).aspx

Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim message1 As String = TextBox1.Text
            My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt", String.Format("how many edges does {0} have?", message1)  , True)
            Process.Start("C:\TestFolder1\test.txt")
        End Sub
    End Class

答案 1 :(得分:0)

如果您的变量属于String类型(在您的情况下message1String),则只需使用+运算符:

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim message1 As String = TextBox1.Text
        My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt", "how many edges does" + " " + message1 + " " + "have?"  , True)
        Process.Start("C:\TestFolder1\test.txt")
    End Sub
End Class

请注意,我添加" "只是为了方便阅读。对于其他数据类型(例如Integer),您可以在添加之前使用ToString()方法将其转换为String

Dim message1 As Integer = 5 'Note that this is an Integer now
My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt", "how many edges does" + " " + message1.ToString() + " " + "have?"  , True)