110,538
社区成员
发帖
与我相关
我的任务
分享
class Program
{
static void Main(string[] args)
{
int n = a();
Console.WriteLine("{0}",n);//2
}
static int a()
{
int x = 1;
try
{
return ++x;
}
catch (Exception e)
{
}
finally
{
++x;
}
return x;
}
}
.method private hidebysig static int32 a() cil managed
{
// 代码大小 35 (0x23)
.maxstack 2
.locals init ([0] int32 x,
[1] class [mscorlib]System.Exception e,
[2] int32 CS$1$0000)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
.try
{
.try
{
IL_0003: nop
IL_0004: ldloc.0
IL_0005: ldc.i4.1
IL_0006: add
IL_0007: dup
IL_0008: stloc.0
IL_0009: stloc.2
IL_000a: leave.s IL_0020
} // end .try
catch [mscorlib]System.Exception
{
IL_000c: stloc.1
IL_000d: nop
IL_000e: nop
IL_000f: leave.s IL_0011
} // end handler
IL_0011: nop
IL_0012: leave.s IL_001b
} // end .try
finally
{
IL_0014: nop
IL_0015: ldloc.0
IL_0016: ldc.i4.1
IL_0017: add
IL_0018: stloc.0
IL_0019: nop
IL_001a: endfinally
} // end handler
IL_001b: nop
IL_001c: ldloc.0
IL_001d: stloc.2
IL_001e: br.s IL_0020
IL_0020: nop
IL_0021: ldloc.2
IL_0022: ret
} // end of method Program::a
IL_000a: leave.s IL_0020
无论try、catch是否leave,最终代码都会执行finally
看IL你会发现:会改变变量值,但是不包含leave
尽快try有return语句,代码还是执行到finally,C#就是这么设计的
最后面的return是执行不到的,IL你可以看不到leave.sIL_000a: leave.s IL_0020
无论try、catch是否leave,最终代码都会执行finally
看IL你会发现:会改变变量值,但是不包含leave
尽快try有return语句,代码还是执行到finally,C#就是这么设计的
最后面的return是执行不到的,IL你可以看不到leave.s
static void Main()
{
int a = aa();
Console.WriteLine("{0}",a);
Console.ReadLine();
}
static int aa()
{
int a = 0;
int b = 1;
try
{
int c = b / a;
Console.WriteLine("1");
}
catch
{
Console.WriteLine("2");
return 0;
}
finally
{
Console.WriteLine("3");
}
return 1;
}
finally
{
++x;
}
return x;
这就无意中自己蒙了自己。
测试需要创意,因此你应该自己去想到要写 x*10000 之类的代码。不要让自己的思想禁锢在特别僵化的“正统”套子中。class Program
{
static void Main(string[] args)
{
int n = a();
Console.WriteLine("{0}", n);//2
}
static int a()
{
int x = 1;
try
{
return ++x;
}
catch (Exception e)
{
}
finally
{
++x;
}
return x * 10000;
}
}