try-finally
class Program { static void Main(string[] args) { Program pr = new Program(); testret ret = pr.dosome(); Console.WriteLine(pr.doint());//值类型 Console.WriteLine(ret.Name);//这里引用类型,方法内对于参数的修改也会带到方法外,这里可以证明就算return语句在try中,finally的代码也一定会执行。 Console.ReadKey(); } private int doint() { int i = 0; try { i = 1; return i; } finally { i = 2; Console.WriteLine("finally int"); } return i; } private testret dosome() { testret re = null; try { re = new testret() { Name = "1" }; return re; } finally { re.Name = "2"; re = null; Console.WriteLine("finally ref"); } } } class testret { public string Name { get; set; } }
doint方法 用reflector查看il代码,如下:
private int doint() { int CS$1$0000; int i = 0; try { i = 1; CS$1$0000 = i; } finally { Console.WriteLine("finally int" + 2); } return CS$1$0000; }
dosome:
private testret dosome() { testret re = null; testret CS$1$0000; try { testret <>g__initLocal0 = new testret { Name = "1" }; re = <>g__initLocal0; CS$1$0000 = re; } finally { re.Name = "2"; re = null; Console.WriteLine("finally ref"); } return CS$1$0000; }
不存在一种打破try-finally执行顺序的情况。除非应用程序在try中退出了。