【问题标题】:MultiLine string inside String.Format()?String.Format() 内的多行字符串?
【发布时间】:2013-09-07 20:34:57
【问题描述】:

我正在尝试简化一些代码行,尝试在 string.format 方法中分配多行字符串,但它在显示“预期表达式”的“”字符处引发异常:

Dim RegistryScript As String = String.Format(<![CDATA[
    Windows Registry Editor Version 5.00
    [HKEY_CURRENT_USER\Environment]
    "PATH"="{0}"
    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
    "PATH"="{1}"
]]></a>.Value, String.Join(";", PATH_Current), String.Join(";", PATH_Local))

所以如果我不能这样做,那么也许我可以做一些类似的字符串技巧?

这是我想让它在代码中更具可读性的原始代码:

' Current user
IO.File.WriteAllText(FilePath, " Windows Registry Editor Version 5.00" & Environment.NewLine, System.Text.Encoding.Unicode)
IO.File.AppendAllText(FilePath, "[HKEY_CURRENT_USER\Environment]" & Environment.NewLine, System.Text.Encoding.Unicode)
IO.File.AppendAllText(FilePath, String.Format("""PATH""=""{0}""", String.Join(";", PATH_Current)) & Environment.NewLine, System.Text.Encoding.Unicode)

' Local Machine
IO.File.AppendAllText(FilePath, " Windows Registry Editor Version 5.00" & Environment.NewLine, System.Text.Encoding.Unicode)
IO.File.AppendAllText(FilePath, "[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]" & Environment.NewLine, System.Text.Encoding.Unicode)
IO.File.AppendAllText(FilePath, String.Format("""PATH""=""{0}""", String.Join(";", PATH_Local)) & Environment.NewLine, System.Text.Encoding.Unicode)

Console.WriteLine(" [+] Backup done!")

我也尝试过使用字符串生成器,但我得到了一些不可读的代码,这就是我尝试将它们全部放在多行字符串中的原因。

【问题讨论】:

    标签: .net vb.net string visual-studio multiline


    【解决方案1】:

    VB.NET 不支持多行字符串,但您可以使用 XML 文字模拟它们。但是,您的文字必须是有效的 XML。要么以&lt;a&gt; 标记开头,要么在末尾省略&lt;/a&gt; 结束标记。

    【讨论】:

    【解决方案2】:

    让自己的事情变得更轻松。

    Using sr As New StreamReader({path})
       sr.WriteLine("whatever")
       sr.writeLine("somemore on next line")
    End Using
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      Dim multi As String = <![CDATA[
          Some
          multiline text
      ]]>.Value
      

      现在你可以这样做了:

      Console.WriteLine(String.Format("multi{0} string = {1}", "line", multi))
      

      【讨论】:

      • 那是 C# 人,看我的代码是 VB.NET,在你的例子中,你分配了一个变量值而不是 String.Format() 的参数,无论如何谢谢......
      • @ElektroHacker 没关系。由于.Value 返回一个字符串,所以.Value 的结果可以作为参数传递给接受字符串的String.Format
      • 请注意,.Value 是一个属性,而不是一个方法,因此不需要括号。
      • @Zev Spitz 您看到并回复了 NullGeo 代码的编辑版本,当我说我的评论是因为 NullGeo 刚刚放入了 @C# 运算符,您知道它不在 VB 中,感谢阅读.
      • 抱歉问题在我回答时被编辑了。 @ElektroHacker,为什么不将注册表文本存储为字符串资源并在运行时使用它?
      猜你喜欢
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-27
      • 2013-08-10
      • 1970-01-01
      • 2010-10-29
      • 1970-01-01
      相关资源
      最近更新 更多