Bri*_*ney 7 c# string escaping verbatim-string
我有以下字符串,将无法编译:
String formLookupPull = @"SELECT value1, '"+tableName+"', '"+columnName+"' FROM lkpLookups WHERE ""table"" = '" + tableName + "' and ""field"" = '" + columnName + "';";
Run Code Online (Sandbox Code Playgroud)
违规部分是:
""table"" =
Run Code Online (Sandbox Code Playgroud)
和
""field"" =
Run Code Online (Sandbox Code Playgroud)
编译器在转义序列上变得混乱.任何人都可以看到什么是错的?
Dan*_*ant 17
解决你的标题问题......
要在逐字字符串文字中转义引号,请使用quote-escape-sequence ""
(这是两个引号字符)
string a = @"He said ""Hi!""..."; // He said "Hi!"...
Run Code Online (Sandbox Code Playgroud)
有关转义等的更多详细信息,请参阅MSDN.
请注意,在您发布的代码中,唯一的逐字字符串是第一个(使用@
之前的字符串).后续字符串不是逐字的,因此适当的转义序列将是\"
.
你可以让它看起来更漂亮string.Format
:
String formLookupPull =
string.Format(@"SELECT value1, '{0}', '{1}' FROM lkpLookups" +
@"WHERE ""table"" = '{0}' and ""field"" = '{1}';",
tableName, columnName)
Run Code Online (Sandbox Code Playgroud)
问题是,并非所有串联的字符串都是逐字字符串文字,只有连接的第一部分是.
换一种说法,
@"SELECT value1, '"
Run Code Online (Sandbox Code Playgroud)
是构建最终字符串的整个语句中唯一的逐字文字.
您需要在字符串的其余部分前面添加@以使其全部逐字.
这将使它看起来像:
String formLookupPull = @"SELECT value1, '"+tableName+ @"', '"+columnName+ @"' FROM lkpLookups WHERE ""table"" = '" + tableName + @"' and ""field"" = '" + columnName + @"';";
Run Code Online (Sandbox Code Playgroud)
你想用来\"
逃避报价,而不是""
.
像这样:
.. FROM lkpLookups WHERE \"table\" = '" ..
Run Code Online (Sandbox Code Playgroud)
编辑:
进一步说明:
你只有@
你所连接的所有字符串中的第一个.在文字字符串(@
前面有一个字符串)中,您可以使用双引号来转义引号.在普通字符串中,它是斜线引用.
例如.
string s = @"this is a literal string with ""quotes"" in it, "
+ "and this is a normal string with \"quotes\" in it";
string t = @"two literal strings" + @", concatenated together.";
Run Code Online (Sandbox Code Playgroud)