c# - ADO 命令文本语法

标签 c# string

有谁知道为什么有时在 commandText 字符串之前使用 @

两者似乎都工作正常。

command.CommandText = @"SELECT id FROM users";

command.CommandText = "SELECT id FROM users";

最佳答案

这是 C# 的逐字字符串文字表示法。

逐字字符串文字前面有一个前导 @ 以及 @ 之后的引号之间的任何内容将被视为字符串文字的一部分,无需转义。

请参阅String literals :

C# supports two forms of string literals: regular string literals and verbatim string literals.

A regular string literal consists of zero or more characters enclosed in double quotes, as in "hello", and may include both simple escape sequences (such as \t for the tab character) and hexadecimal and Unicode escape sequences.

A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.

很可能一个查询跨越多行,编写代码的人都想像这样把它放在多行上:

command.CommandText = @"SELECT id
                       FROM users";

如果没有逐字字符串文字,您将不得不这样做:

command.CommandText = "SELECT id"
                      + " FROM users";

关于c# - ADO 命令文本语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1162390/

相关文章:

c# - 从 Controller 的方法重定向到 ~/Shared/Error.cshtml

c - 如何将 vasprintf() 与特殊字符 (%) 一起使用?

c# - 从代码隐藏运行 javascript 函数

c# - 'CryptoStream' 的最佳重载没有名为 'leaveOpen' 的参数

java - 将用户输入字符串与从文本文件读取的字符串进行比较

javascript - 在 3 个不同的字符串之后和双引号之间替换字符串

c - 为什么字符串修改没有按预期进行?

java - 如何判断一个字符串是否可以生成另一个字符串

c# - 创建迁移文件时如何为列分配不同的默认值

c# - 最小堆是否按 "default"排序