• @ 在 C# string 中的用法


    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

  • 相关阅读:
    图片《小美眉》
    redhat基本知识
    Linux 求助。设置分辨率?

    PHP close
    别想一个人承担一切
    java charAt返回char,不是int
    我的计算器
    支付宝面试小贴士
    java string charAt length()疑惑
  • 原文地址:https://www.cnblogs.com/terrorpig/p/1367431.html
Copyright © 2020-2023  润新知