[英]Catch unhandled exception and stop method?
在 windows 窗體應用程序中,類的List<>
將通過方法進行檢查,其返回類型為 bool。
例如,如果有 100 個類並且只有 1 個類返回false
那么它的另一個字段( Reqbool
)將是fals
e。 當所有類都得到true
回報時,只有Reqbool
才會為true
。
有什么簡單的方法可以解決這個問題嗎? 它說異常未處理,每個false
返回都顯示消息框。
bool Reqbool = true;
bool MiniReqbool;
if(MiniReqbool == false) { throw new Exception(); }
try
{
for (int i = 0; i < ImportList.Count; i++)
{
MiniMiniTest mitest = new MiniMiniTest();
MiniReqbool = mitest.ReqTest(ImportList[i], QValue);
}
}
catch (Exception)
{
Reqbool = false;
MessageBox.Show("Sorry points not found");
}
在 try catch 之前拋出異常。 如果您在檢查之后放置 if 語句,則應該修復它。
bool Reqbool = true;
bool MiniReqbool;
try
{
for (int i = 0; i < ImportList.Count; i++)
{
MiniMiniTest mitest = new MiniMiniTest();
MiniReqbool = mitest.ReqTest(ImportList[i], QValue);
if(MiniReqbool == false) { throw new Exception(); }
}
}
catch (Exception)
{
Reqbool = false;
MessageBox.Show("Sorry points not found");
}
正如評論中所建議的那樣,最好毫無例外地執行此操作,這仍然可以按照您像這樣工作的方式來完成。
bool Reqbool = true;
bool MiniReqbool = true;
for (int i = 0; i < ImportList.Count; i++)
{
MiniMiniTest mitest = new MiniMiniTest();
if(!mitest.ReqTest(ImportList[i], QValue)) { MiniReqbool = false; }
}
if (MiniReqbool == false)
{
Reqbool = false;
MessageBox.Show("Sorry points not found");
}
這聽起來像你想設置Reqbool
到false
只有當所有的項目ImportList
返回true
的mitest.ReqTest
。 在這種情況下,您可以使用 Linq 和擴展方法All
:
MiniMiniTest mitest = new MiniMiniTest();
Reqbool = ImportList.All(il => mitest.ReqTest(il, QValue));
如果您想要每個項目一個新的MiniMiniTest
,您可以使用以下內容:
for (int i = 0; i < ImportList.Count; i++)
{
MiniMiniTest mitest = new MiniMiniTest();
if (!mitest.ReqTest(ImportList[i], QValue))
{
Reqbool = false;
break;
}
}
或者使用foreach
循環使其更簡單:
foreach (var item in ImportList) //...
旁注以下代碼:
bool MiniReqbool;
if(MiniReqbool == false) { throw new Exception(); }
總是會拋出異常,因為bool
的默認值是false
所以我認為這不是您的實際代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.