【问题标题】:Concatenating To A Verbatim String Literal With Large Volume Of Text Breaking Into New Line [duplicate]将大量文本插入换行符连接到逐字字符串文字[重复]
【发布时间】:2018-02-07 03:23:20
【问题描述】:

如何在逐字字符串文字中连接一个变量,其中有大量文本插入换行符?我正在使用字符串生成器来附加所有字符串变量,但

我打算做什么 -

StringBuilder sbuilder = new StringBuilder();
variable y = something
variable x = @"text"+ y + "
             other text other text";
variable z = @"blablabla";
variable z2 = @"some other text"

sbuilder.Append(x);
sbuilder.Append(z);
sbuilder.Append(z2);

string html = sbuilder.ToString();

我尝试了什么 -

var variable = modelview.something; 
string form = @"a whole lotta text "+variable+ "even more text";

我遇到了语法错误

Represents text as a series of Unicode characters.To browse the .NET framework source code for this type, see the Reference Source.
Newline in constant

【问题讨论】:

  • 如果您有错误,请显示您的代码并提供消息。
  • 就像你连接一个普通的字符串一样。 string str = @"a" + "b";
  • 我实际上编辑了我的问题,因为它与他们声称是重复但仍然被否定和禁止的问题不同。嘘。

标签: c# asp.net string-concatenation


【解决方案1】:

有几种方法。

一种是经典的方式

var variable = modelview.something; 
string form = @"a whole lotta text " + variable + @" even more text";

另一种方法是使用$ 字符串插值

var variable = modelview.something; 
string form = $@"a whole lotta text {variable} even more text";

这段代码相当于

var variable = modelview.something; 
string form = string.Format(@"a whole lotta text {0} even more text", variable);

【讨论】:

    【解决方案2】:

    也许你正在寻找这样的东西。

    string myVar = "hello";
    string form = $@"My String {myVar}";
    

    【讨论】:

      【解决方案3】:

      或者通过插值

      string from = $@"a whole lotta text {variable} even more text";
      

      或通过连接

      string from = @"a whole lotta text" + variable + @"even more text";
      

      【讨论】:

        【解决方案4】:

        您可以随时使用string.Concat()

        string a = @"a";
        string b = @"b";
        
        string.Concat(a, b); // returns "ab"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-06
          • 2014-03-11
          相关资源
          最近更新 更多