简体   繁体   English

C#发生异常时跳过foreach循环

[英]C# Skip foreach loop when exception

The ListItems has one item which always gives type mismatch exception. ListItems具有一项始终会提供类型不匹配异常的项目。 The code line 'MyItem items in ListItems' cause the exception to raise as there is some type mismatch between Listitems and MyItem. 代码行“ ListItems中的MyItem项目”导致引发异常,因为Listitems和MyItem之间存在某些类型不匹配。 How do I ignore the type mismatch exception and move to the next element. 如何忽略类型不匹配异常并移至下一个元素。 If it would enter inside the foreach loop, I could have used the 'continue'. 如果它将进入foreach循环内,则可以使用“继续”。 But the code does not even enter the for each loop 但是代码甚至没有为每个循环输入

foreach (MyItem items in ListItems)
{
   ...Do...
}

I would recommend using IEnumerable.OfType . 我建议使用IEnumerable.OfType This is like using an is MyItem test on each item, and only selecting - and thus looping over - the items where such a test is true. 这就像对每个项目使用is MyItem测试,并且仅选择-从而遍历-这样的测试为真的项目。 (It actually also performs a cast, which ensures the excepted result sequence type, but only if it can .) (实际上,它也执行强制类型转换,以确保排除结果序列类型,但前提是可以)

foreach (var items in ListItems.OfType<MyItem>()) {
   // items not "of" MyItem will be skipped
}

On the other hand, the original code is like a direct (MyItem) cast on each item, which can fail with a InvalidCastException . 另一方面,原始代码就像直接对每个项目(MyItem)进行强制转换 ,可能会因InvalidCastException而失败。

You need to filter out so only the MyItem items are processed. 您需要过滤掉,以便仅处理MyItem项目。 Be sure to include the System.Linq namespace and do 确保包括System.Linq命名空间并执行

foreach (MyItem items in ListItems.OfType<MyItem>())
{
   ...Do...
}

That will filter your list and only return the items in it that derive from MyItem 这将过滤您的列表,并且仅返回从MyItem派生的项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM