C# 如何标记一个方法将无条件抛出?
有没有一种方法可以修饰一个方法,该方法将执行一些日志记录,然后无条件地抛出异常,就这样 我有这样的代码:C# 如何标记一个方法将无条件抛出?,c#,.net,exception-handling,attributes,C#,.net,Exception Handling,Attributes,有没有一种方法可以修饰一个方法,该方法将执行一些日志记录,然后无条件地抛出异常,就这样 我有这样的代码: 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; }
// 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." );
}
有什么建议吗?谢谢。如果您知道异常总是会被抛出,那么这又有什么关系呢。只需将变量设置为可以编译的值:
void foo(out int x)
{
if( condition() ) { x = bar(); return; }
x = 0;
MyMethodThatAlwaysThrowsAnException( "missed something." );
}
它不能回答您的问题,但当使用out参数时,最好在方法的开头初始化它们。这样您就不会有任何编译器错误:
void foo(out int x)
{
x = 0;
if( condition() ) { x = bar(); return; }
MyMethodThatAlwaysThrowsAnException( "missed something." );
}
x
是一个out参数,必须在向前移动之前进行设置无法以这种方式标记方法
可能与此无关,但示例中使用out
参数的模式有点奇怪。为什么不在方法上使用一个返回类型呢
int Foo()
{
if (condition()) return bar();
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);
}
如果不想设置x,为什么不使用ref参数呢
void foo(ref int x)
{
if( condition() ) { x = bar(); return; }
// nobody complains about anything
MyMethodThatAlwaysThrowsAnException( "missed something." );
}
这是一个非常古老的线程,但我只想补充一点,您应该从一开始就编写它:
void foo(out int x)
{
if (!condition())
MyMethodThatAlwaysThrowsAnException("missed something.");
x = bar();
// and so on...
}
这样编译器就不会抱怨,您的代码也就更清晰了。您遇到了什么问题?“x有out属性,并且在方法末尾还没有设置”我很困惑-如果在设置x时没有抛出它(并且返回完成),如何无条件地抛出它我想将MyMethodThathawaysThrowsanException标记为总是抛出异常的方法,而不是foo方法。我想知道guard子句的答案在哪里。我认为倒转逻辑是一个更好的答案。这正是我想避免做的事。:)除非抛出异常,否则确保在方法的早期设置任何out参数并为其分配默认值仍然是一个好策略。这只是一个简单的示例。实际的代码相当复杂。@k0dek0mmand0:我怀疑可能是这样的。我猜你运气不好-没有办法告诉编译器总是抛出异常的
MyMethodThrowsanException
。我认为应该在有意义的地方分配out参数,或者因为它可以防止编译时出现一些隐藏的bug,因为你忘了在某些代码路径上分配out参数。实际代码可能更复杂复杂,因此您的建议可能没有意义。