现在的位置: 首页 > 综合 > 正文

@ 在 C# string 中的用法

2012年04月18日 ⁄ 综合 ⁄ 共 1841字 ⁄ 字号 评论关闭

1。 C# 中 字符串常量可以以 @ 开头声名,这样的优点是转义序列“不”被处理,按“原样”输出,
即我们不需要对转义字符加上 (反斜扛),就可以轻松coding。如
string filePath = @"c:DocsSourcea.txt"; // rather than "c:DocsSourcea.txt"
 
2。如要在一个用 @ 引起来的字符串中包括一个双引号,就需要使用两对双引号了。
这时候你不能使用 来转义爽引号了,因为在这里 的转义用途已经被 @  “屏蔽”掉了。如
@"""Ahoy!"" cried the captain."; // 输出为: "Ahoy!" cried the captain.
有点像SQL中的单引号常量处理方式:
DECLARE @msg varchar(100)
SET @msg = ''Ahoy!'' cried the captain.' -- 输出为: 'Ahoy!' cried the captain.

3。@ 会识别换行符
其实这个特性,我不知道怎么描述,只是偶然发现的,先看下面的代码吧:
string script = @"
            <script type=""type/javascript"">
            function doSomething()
            {
            }
            </script>";

在cs文件中写js,结构就很清晰了,正常情况我们是这样coding的:
string script2 = "<script type="type/javascript">function doSomething(){}</script>";
// or
string script3 =
            "<script type="type/javascript">" +
            "function doSomething(){ " +
            "}</script>";
通常我们会选择后者,因为js代码一般比较长,或者方法体很大,或者需要连接其他变量,这样结构比较清晰。
注意:如果“拼接”的次数很多,应该考虑使用StringBuilder了,有助于提高性能。
还有一种场景,也很常见,在程序中拼接 SQL 语句,如
private const string SQL_INS_USER = @"
            INSERT INTO t_User([UserName], [Password], Email)
                        VALUES(@UserName, @Password, @Email)";
 
然而,我们需要关注一个问题:字符串长度
看下面的测试代码:
private const string SQL_INS_USER1 = @"
        INSERT INTO t_User([UserName], [Password], Email)
                    VALUES(@UserName, @Password, @Email)";
private const string SQL_INS_USER2 = @"INSERT INTO t_User([UserName], [Password], Email)
                    VALUES(@UserName, @Password, @Email)";

private const string SQL_INS_USER3 = @"INSERT INTO t_User([UserName], [Password], Email)
                                     VALUES(@UserName, @Password, @Email)";

static void Main(string[] args)
{
    Console.WriteLine(SQL_INS_USER1.Length); // 126
    Console.WriteLine(SQL_INS_USER2.Length); // 112
    Console.WriteLine(SQL_INS_USER3.Length); // 86
}
可以看到三个字符串长度分别相差了,14=126-112和26=112-86,在代码编辑器中,SQL_INS_USER1
中第一个换行符号之后,缩进13个空格(INSERT之前),而
SQL_INS_USER2 中第一个换行符号之后,缩进25个空格(VALUES之前),
那么,加上一个换行符,刚刚好 14和26

抱歉!评论已关闭.