2017-05-04 91 views
-2

在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"); 
} 
+0

你的問題真的不清楚,那可能是語言障礙。我想你正在尋找'Enumerable.All()'或'Enumerable.Any()',但我不能告訴。 – Jamiec

+0

因此,如果'mitest.ReqTest'返回''false'爲'ImportList'中的任何項目,您希望'Reqbool'爲'false'? – TheLethalCoder

+0

@ TheLethalCoder絕對是! – ldn

回答

2

這聽起來像你想設置Reqboolfalse只有在ImportListmitest.ReqTest回報true所有項目。在這種情況下,你可以使用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) //... 

附註下面的C頌:

bool MiniReqbool; 
if(MiniReqbool == false) { throw new Exception(); } 

總是會拋出異常的boolfalse默認值,所以我想這是不是你的實際代碼。

+0

我確實認爲你的附註是他的實際代碼,他提到像「它說異常未處理」的東西,這正是如果你把投擲放在捕捉之前會發生什麼。 – Kyra

2

您在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"); 
} 
+1

當然,使用異常進行流量控制並不是一個好主意...... –

+0

的確,我會毫無例外地更新自己的答案 – Kyra

+1

備註:在所提出的代碼中,不需要'MiniReqbool'在所有... – TheLethalCoder