在C#中,@符号不仅可以加在字符串常量之前,使字符串不作转义之用,还可以加在变量名之前,使变量名与关键字不冲突,这种用法称为“逐字标识符”。请看下面的代码:

1
2
3
4
5
6
7
8
9
class @class
{
    public static void @static(bool @bool) {
        if (@bool)
            System.Console.WriteLine("true");
        else
            System.Console.WriteLine("false");
    }
}

这里使用到@的地方有三处,@class,@static和@bool,如果不加@的话,他们都是关键字,编译就会报错。加了@之后,他们和普通的变量名没有区别了,可以正常使用。当然@也可以加在非关键字之前,比如:

1
2
3
4
static void Test(string @str)
{
    Console.WriteLine(str);
}

这样@就一点效果也没有,@str等价于str。

当然,使用关键字作为变量名是非常不推荐的,除非特殊情况,比如和其它语言交互,一般不鼓励使用。

您还可能感兴趣的日志:

  1. PowerShell Cmdlet的测试 (一)SDK
  2. 经典面试题 之 数组的循环右移
  3. PowerShell Cmdlet的测试 (二) 获取结果
  4. C#中重载相等运算符
  5. 经典面试题 之 洗牌问题

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

   
© 2004 - 2011 Leona+Suffusion theme by Sayontan Sinha