我有这样的代码:
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# – 如何标记方法将无条件抛出?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)