c# – 如何标记方法将无条件抛出?
发布时间:2020-12-15 06:20:22 所属栏目:百科 来源:网络整理
导读:有没有办法装饰一些方法来做一些日志记录,然后无条件抛出异常呢? 我有这样的代码: void foo(out int x){ if( condition() ) { x = bar(); return; } // notice that x is not yet set here,but compiler doesn't complain throw new Exception( "missed so
有没有办法装饰一些方法来做一些日志记录,然后无条件抛出异常呢?
我有这样的代码: void foo(out int x) { if( condition() ) { x = bar(); return; } // notice that x is not yet set here,but compiler doesn't complain throw new Exception( "missed something." ); } 如果我尝试这样写,我会遇到一个问题: void foo(out int x) { if( condition() ) { x = bar(); return; } // compiler complains about x not being set yet MyMethodThatAlwaysThrowsAnException( "missed something." ); } 有什么建议么?谢谢. 解决方法
这个怎么样?
bool condition() { return false; } int bar() { return 999; } void foo(out int x) { if (condition()) { x = bar(); return; } // compiler complains about x not being set yet throw MyMethodThatAlwaysThrowsAnException("missed something."); } Exception MyMethodThatAlwaysThrowsAnException(string message) { //this could also be a throw if you really want // but if you throw here the stack trace will point here return new Exception(message); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |