首页 > 代码库 > try-catch-finally
try-catch-finally
通过中间代码窥探try-catch-finally本质:
class Program { static void Main(string[] args) { Program p = new Program(); Console.WriteLine(p.Test1()); //Console.WriteLine(p.Test2()); Console.Read(); } //结果为:3 private TestClass Test1() { TestClass tc = new TestClass(); try { tc.testVar = 2; return tc; } catch (Exception) { throw; } finally { tc.testVar = 3; } } //结果为:2 private int Test2() { int test = 1; try { test = 2; return test; } catch (Exception) { throw; } finally { test = 3; } } } class TestClass { public int testVar = 111; public override string ToString() { return testVar.ToString(); } }
调用方法Test2,try中return时,已经将返回值保存在中间代码的本地变量中,而不再是源码中变量test,所以finally的操作是无效的。其中间代码为:
try-catch-finally
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。