用“@”符号连接字符串中的变量

时间:2015-12-18 04:51:07

标签: c# string-concatenation

给出这个多行字符串:

string strProviderJSON = @"
                {
                    ""npi"":""1111111111"",
                    ""name"":""DME Clearinghouse"",
                    ""email"":""my@doc.como"",
                    ""contactName"":""Sally Smith"",
                    ""fax"":"""",
                    ""address"":{
                        ""country"":""United States"",
                        ""street1"":""27787 Dequindre Apt 616"",
                        ""street2"":"""",
                        ""city"":""Madison Heights"",
                        ""state"":""MI"",
                        ""zipCode"":""32003""
                    },
                    ""phone"":""(904) 739-0300"",
                    ""contactPhone"":""(904) 739-0300""
                }
            ";

如何在那里连接变量?我尝试了这个,但一直收到错误:

string strTest = "1111111111";
string strProviderJSON = @"
                {
                    ""npi"":""" + strTest + """,
                    ""name"":""DME Clearinghouse"",
                    ""email"":""my@doc.como"",
                    ""contactName"":""Sally Smith"",
                    ""fax"":"""",
                    ""address"":{
                        ""country"":""United States"",
                        ""street1"":""27787 Dequindre Apt 616"",
                        ""street2"":"""",
                        ""city"":""Madison Heights"",
                        ""state"":""MI"",
                        ""zipCode"":""32003""
                    },
                    ""phone"":""(904) 739-0300"",
                    ""contactPhone"":""(904) 739-0300""
                }
            ";

2 个答案:

答案 0 :(得分:4)

将另一个@字符粘贴到下一个字符串文字的开头。

...
""npi"":""" + strTest + @"""
""name"": ""DME Clearinghouse"",
...

答案 1 :(得分:1)

对于字符串连接,您应该使用 String.Format()方法,因为正常连接会在内存中创建多个字符串,因此String.Format()将帮助您轻松地插入变量。

示例:

String s = "111111";
String finalString = String.Format(@""npi"":""{0}"",s);

这是针对单行的(您可以使用多行,但这不可读)。 现在对于多行,您可以使用 StringBuilder 类,它为我们提供了许多功能,如追加() AppendFormat()等所以使用它你可以有一个可读的代码

示例:

StringBuilder tempString = new StringBuilder();
tempString.Append("{\n");
tempString.AppendFormat(@"""npi"":""{0}"",\n", npiString);// npiString is a variable
tempString.AppendFormat(@"""name"":""{0}"",\n", nameString);// nameString is a variable
.....
// you should add variables like this
// at the end you can store final string by using following
String finalString = tempString.ToString();

注意:我没有在String中多次使用这些'“',所以不确定,但是附加变量应该由 StringBuilder 完成。

希望它可以帮助你实现目标。

相关问题