C# 常量错误中的新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17739612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:22:37  来源:igfitidea点击:

New Line in Constant error

c#.netstringinsert

提问by Furquan Khan

I am writing a c# code in which i am fetching values from the database and using it. The problem i am facing is as below.

我正在编写 ac# 代码,其中我从数据库中获取值并使用它。我面临的问题如下。

If my fetched value from the database is :

如果我从数据库中获取的值是:

 string cat1 = "sotheby's";

now while using this cat i want to insert an escape character before single quote, to achieve this i have written the below code:

现在在使用这只猫时,我想在单引号前插入一个转义字符,为此我编写了以下代码:

  string cat1 = "sotheby's";
                    if (cat1.Contains("'")) {
                        var indexofquote = cat1.IndexOf("'");
                        cat1.Insert(indexofquote-1,"\");
                        var cat2 = cat1;
                    }

The error rises in insert line, the backslash(escape character). The error is New Line in Constant. Please help me how to correct this error.

错误出现在插入行、反斜杠(转义字符)中。错误是常量中的新行。请帮助我如何更正此错误。

采纳答案by Henk Holterman

You can't just write "\"in C# code. That will produce the "New Line in Constant" error because it 'escapes' the second quote so that it doesn't count. And the string isn't closed.

你不能只用"\"C# 代码编写。这将产生“常量中的新行”错误,因为它“转义”了第二个引号,因此它不计算在内。并且字符串没有关闭。

Use either "\\"(escaping the \with itself)
or use @"\"(a verbatim string).

使用"\\"\与自身转义)
或使用@"\"(逐字字符串)。

回答by user1847879

That will only replace 1 single quote. To get them all use:

那只会替换 1 个单引号。要让它们全部使用:

string cat1_escaped = cat1.Replace("'", "\'");

Although a lot of databases don't escape quotes like that, but rather by doubling them:

尽管很多数据库不会像这样转义引号,而是将它们加倍:

string cat1_escaped = cat1.Replace("'", "''");

回答by nodots

The Backslash in string literals is an escape character, so it must either be escaped itself:

字符串文字中的反斜杠是转义字符,因此必须对其自身进行转义:

"\"

Or you can use a so-called verbatim string literal:

或者您可以使用所谓的逐字字符串文字:

@"\"

See: http://msdn.microsoft.com/en-us/library/aa691090.aspx

请参阅:http: //msdn.microsoft.com/en-us/library/aa691090.aspx

Regarding your compile error: The backslash escapes the following quotation mark, thus the string literal is not recognized as closed. The following characters ) and ; are valid for string literals, however the line ending (newline) is not. Hence the error.

关于您的编译错误:反斜杠转义以下引号,因此字符串文字不被识别为关闭。以下字符 ) 和 ; 对字符串文字有效,但行尾(换行)无效。因此错误。