C# - 如果发生错误,则继续执行 foreach() 循环
我目前有一个列表视图和一个充满 XML 文档的文件夹。我使用 foreach() 循环来遍历所有 XML 文件并将数据相应地加载到列表视图中。我的问题是,如果 in 中存在错误(例如:如果其中一个 XML 文件不完全有效、包含错误等),并且仍然将数据添加到列表视图中,我该如何继续执行 foreach() 循环?我不是问如何解析 XML 或如何将其加载到列表视图中,我知道该怎么做,只是不知道如果发生错误如何继续循环。
I currently have a listview and a folder full of XML documents. I am using a foreach() loop to go through all the XML files and load data into the listview accordingly. My question is, how do I carry on with the foreach() loop if there is an error within in (example: if one of the XML files is not completely valid, contains errors, etc) and still add the data to the listview? I'm not asking how to parse the XML or how to load it into the listview, that much I know how to do, just not how to proceed with the loop if an error occurs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
你想要:
Do you want:
将循环的内部内容包装在
try ... catch
块中。例如
Wrap the inner contents of the loop in a
try ... catch
block.e.g.
你不会这样做吗
wouldnt you do
您可以在 try catch 块中进行文件处理并处理错误情况。您可以在 catch 中优雅地处理错误并继续加载数据。
You can do the file processing in a try catch block and handle the error condition. You can handle the errors gracefully in catch and continue with loading of data.
我认为你应该这样做:
I think you should do this:
如果您的处理代码引发异常,请使用
try/catch
块。如果您使用if
块检查某个方法的结果,请使用continue
。If your processing code throws exceptions, then use a
try/catch
block. If you're checking the results of some method with anif
block, then usecontinue
.如果您需要更频繁地使用它或者您只是想拥有更优雅的代码,您可以使用 lambda 表达式和委托来为此目的创建一个新的抽象:
然后您可以只编写:
但是,在发生错误的情况下使用异常预计这不是最好的编程风格。如果您可以编写一个方法,例如
IsValid
,如果文档有效则返回 true,那么您可以编写:If you need to use this more often or if you just want to have more elegant code, you can use lambda expressions and delegates to create a new abstraction for this purpose:
Then you can write just:
However, using exceptions in situations where an error is expected is not the best programming style. If you can write a method, say
IsValid
that returns true if the document is valid, then you could write: