![](/img/trans.png)
[英]How to stop execution of a method based on calling of another method in c#
[英]How to stop the execution of the calling parent method in c#?
調用父方法:
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
}
被調用的方法:
public bool CheckStr(string str)
{
if (str == "error")
{
return false;
}
// ...additional checks
return true;
}
有沒有辦法如果CheckStr()
返回false
它還會阻止Scripts()
方法進一步執行?
現在我必須在Script()
方法中做一堆if
檢查,感覺有點像我在重復自己的if statement
在每個CheckStr()
之后做同樣的事情。 如果CheckStr()
停止執行Script()
會更好。 這樣的事情可能嗎?
是的,您可以拋出異常。
它將中斷調用“父母”(和他們的“父母”),直到某個地方有一個執行處理程序(try-catch 塊)。 只是谷歌拋出異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.