为什么我们应该在asp.net的sql查询之前编写@?

Sha*_*lni 2 asp.net verbatim

假设我们想从数据库中选择数据,然后我们为此编写查询.

例:

SqlConnection con=new SqlConnection(Connetion name)
string selectPkId = @"SELECT PK_ID FROM TABLE"
SqlCommand cmd=new SqlCommand(selectPkId ,con);
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是为什么我们在sql查询之前基本上使用@.如果我之前没有使用@那么它再次正常工作(不会给出任何错误),那么使用"@"需要什么?请告诉我.

Nul*_*ion 7

这是一个逐字字符串.这意味着保留换行符并忽略转义序列:

string a = "hello, world";                  // hello, world
string b = @"hello, world";               // hello, world
string c = "hello \t world";               // hello     world
string d = @"hello \t world";               // hello \t world
string e = "Joe said \"Hello\" to me";      // Joe said "Hello" to me
string f = @"Joe said ""Hello"" to me";   // Joe said "Hello" to me
string g = "\\\\server\\share\\file.txt";   // \\server\share\file.txt
string h = @"\\server\share\file.txt";      // \\server\share\file.txt
Run Code Online (Sandbox Code Playgroud)

MSDN参考:字符串文字

当您希望保留转义序列而不必双重转义时,这会派上用场,例如:

string sql = @"UPDATE table SET comment='Hello\nWorld'"
// equivalent to:
string sql = "UPDATE table SET comment='Hello\\nWorld'"
Run Code Online (Sandbox Code Playgroud)

当然这是一个非常简单的例子,但大多数时候它会给你一个更易读的字符串.