C# 捕获未处理的异常并停止方法?

C# 捕获未处理的异常并停止方法?,c#,C#,在windows窗体应用程序中,类的列表将通过方法进行检查,其返回类型为bool 例如,如果有100个类,只有1个类返回false,那么另一个字段(Reqbool)将是false。当所有类都返回true时,只有Reqbool将为true 有什么简单的方法可以解决这个问题吗?它表示异常未处理,每个false返回时都会显示messagebox bool Reqbool = true; bool MiniReqbool; if(MiniReqbool == false) { throw new Exc

在windows窗体应用程序中,类的列表将通过方法进行检查,其返回类型为bool

例如,如果有100个类,只有1个类返回
false
,那么另一个字段(
Reqbool
)将是
fals
e。当所有类都返回
true
时,只有
Reqbool
将为
true

有什么简单的方法可以解决这个问题吗?它表示异常未处理,每个
false
返回时都会显示messagebox

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");
}
bool Reqbool=true;
bool-MiniReqbool;
如果(MiniReqbool==false){抛出新异常();}
尝试
{
对于(int i=0;i
在尝试捕获之前抛出异常。如果在检查后放置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;
尝试
{
对于(int i=0;i
正如评论中所建议的那样,最好毫无例外地这样做,这仍然可以按照您现在这样工作的方式来完成

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");
}
bool Reqbool=true;
bool MiniReqbool=true;
对于(int i=0;i
听起来您想将
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;
    }
}

请注意以下代码:

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

将始终抛出异常,因为
bool
的默认值为
false
,因此我假设这不是您的实际代码。

您的问题确实不清楚,这可能是语言障碍。我想你是在寻找
Enumerable.All()
Enumerable.Any()
但我说不出来。所以如果
mitest.ReqTest
返回
false
对于
ImportList
中的任何项目,你想
Reqbool
成为
false
?@TheLethalCoder绝对是!没错,我会毫无例外地更新我的答案。我确实认为你的旁注是他的实际代码,他提到了类似“它说异常未处理”的东西,这正是如果你在接球之前抛球会发生的事情。
bool MiniReqbool;
if(MiniReqbool == false) { throw new Exception(); }