c# – 如何标记方法将无条件抛出?

c# – 如何标记方法将无条件抛出?,第1张

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

我有这样的代码:

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);}
总结

以上是内存溢出为你收集整理的c# – 如何标记方法将无条件抛出?全部内容,希望文章能够帮你解决c# – 如何标记方法将无条件抛出?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1257527.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存