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

前端之家收集整理的这篇文章主要介绍了c# – 如何标记方法将无条件抛出?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法装饰一些方法来做一些日志记录,然后无条件抛出异常呢?

我有这样的代码

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);
}
原文链接:https://www.f2er.com/csharp/95835.html

猜你在找的C#相关文章