在C#中用@ 定义和默认标识符同名的变量名

我们可以用@去起一个和C#内置标志符同名的表示符。

比如

string @string = "string";
Console.WriteLine(@string);

string @test = "test";
Console.WriteLine(test);
string _test1 = "test1";
Console.WriteLine(_test1);

 

 

下面是IL代码可以看到不同之处

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       91 (0x5b)
  .maxstack  2
  .locals init ([0] string s,
           [1] string 'string',
           [2] string test,
           [3] string _test1,
           [4] string[] CS$6$0000,
           [5] int32 CS$7$0001,
           [6] bool CS$4$0002)
  IL_0000:  nop
  IL_0001:  nop
  IL_0002:  ldarg.0
  IL_0003:  stloc.s    CS$6$0000
  IL_0005:  ldc.i4.0
  IL_0006:  stloc.s    CS$7$0001
  IL_0008:  br.s       IL_001f
  IL_000a:  ldloc.s    CS$6$0000
  IL_000c:  ldloc.s    CS$7$0001
  IL_000e:  ldelem.ref
  IL_000f:  stloc.0
  IL_0010:  nop
  IL_0011:  ldloc.0
  IL_0012:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0017:  nop
  IL_0018:  nop
  IL_0019:  ldloc.s    CS$7$0001
  IL_001b:  ldc.i4.1
  IL_001c:  add
  IL_001d:  stloc.s    CS$7$0001
  IL_001f:  ldloc.s    CS$7$0001
  IL_0021:  ldloc.s    CS$6$0000
  IL_0023:  ldlen
  IL_0024:  conv.i4
  IL_0025:  clt
  IL_0027:  stloc.s    CS$4$0002
  IL_0029:  ldloc.s    CS$4$0002
  IL_002b:  brtrue.s   IL_000a
  IL_002d:  ldstr      "string"
  IL_0032:  stloc.1
  IL_0033:  ldloc.1
  IL_0034:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0039:  nop
  IL_003a:  ldstr      "test"
  IL_003f:  stloc.2
  IL_0040:  ldloc.2
  IL_0041:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0046:  nop
  IL_0047:  ldstr      "test1"
  IL_004c:  stloc.3
  IL_004d:  ldloc.3
  IL_004e:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0053:  nop
  IL_0054:  call       valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey()
  IL_0059:  pop
  IL_005a:  ret
} // end of method Program::Main

 

可以看出其实这里@只会对内置的标识符是有用的。

posted on 2015-06-30 17:12  一篑  阅读(1410)  评论(0编辑  收藏  举报

导航