有没有办法装饰一些方法来做一些日志记录,然后无条件抛出异常呢?
我有这样的代码:
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); }