2015-02-10 61 views
-4

请告诉我如何从CheckStr()停止执行Script()停止执行另一种方法的方法

例如

public void Script() 
{ 
// ... 
    string str = "error"; 
    CheckStr(str); 
// ... 
} 
public void CheckStr(string str) 
{ 
    if (str == "error") 
    { 
     // stop Script(); 
    } 
} 
+0

目前还不清楚你在问什么。在checkstr中抛出异常? – Carra 2015-02-10 14:35:41

+1

'Application.Exit()'是“停止”它的执行的一种方法..让用户知道发生了什么虽然会更好...您尝试/研究过什么? – Sayse 2015-02-10 14:39:02

+0

@Sayse我知道我可以使用'return'来停止方法。但它变成了太多的代码。我认为这是不可能的。我想我的问题是不可能解决的。 – user3650075 2015-02-10 14:44:24

回答

1

您可以让CheckStr()返回值:

public void Script() 
{ 
    string str = "error"; 
    if (!CheckStr(str)) 
    { 
     return; 
    } 

    // ...continue 
} 

public bool CheckStr(string str) 
{ 
    if (str == "error") 
    { 
     return false; 
    } 

    // ...additional checks 

    return true; 
} 
1

最简单的办法是有CheckStr返回结果,例如true/false

public bool CheckStr(string str) 
{ 
    if (str == "error") 
    { 
     return false; 
    } 
    ... 
    return true; 
} 

public void Script() 
{ 
    // ... 
    string str = "error"; 
    if (CheckStr(str) == false) 
    { 
     return; 
    } 
    // ... 
} 
1

你可以从CheckStr抛出一个异常,但我不知道这会解决您的具体问题:

public void CheckStr(string str) 
{ 
    if (str == "error") 
    { 
     throw new Exception(); 
    } 
} 

然后,您可以抓住它,无论是在Script,或其它地方:

public void Script() 
{ 
// ... 
    string str = "error"; 
    try { 
     CheckStr(str); 
    } 
    catch 
    { 
     // handle excpetion here. 
    } 
// ... 
}