[英]How to stop the execution of the calling parent method in c#?
The calling parent method:调用父方法:
public void Script()
{
string str = "some text";
var someText = !CheckStr(str);
if (someText)
{
return;
}
str = "some other text";
var someOtherText = !CheckStr(str);
if (someOtherText)
{
return;
}
str = "some other other text";
var someOtherOtherText = !CheckStr(str);
if (someOtherOtherText )
{
return;
}
// ...continue
}
The method that is being called:被调用的方法:
public bool CheckStr(string str)
{
if (str == "error")
{
return false;
}
// ...additional checks
return true;
}
Is there a way that if CheckStr()
returns false
that it also stops the Scripts()
method from further executing?有没有办法如果
CheckStr()
返回false
它还会阻止Scripts()
方法进一步执行?
Right now I have to do a bunch of if
checks in the Script()
method, it feels a bit like I'm repeating myself with the if statement
doing the same thing after each CheckStr()
.现在我必须在
Script()
方法中做一堆if
检查,感觉有点像我在重复自己的if statement
在每个CheckStr()
之后做同样的事情。 It would be better if the CheckStr()
halts te execution of Script()
.如果
CheckStr()
停止执行Script()
会更好。 Is something like this possible?这样的事情可能吗?
Yes, you can throw a exception.是的,您可以抛出异常。
It will interrupt calling "parents" (and their "parents") until a execption-handler is somewhere (try-catch block).它将中断调用“父母”(和他们的“父母”),直到某个地方有一个执行处理程序(try-catch 块)。 Just google for exception-throwing.
只是谷歌抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.