.NET 迭代器包装抛出 API
我有一个带有 API 的类,它允许我请求对象,直到它抛出 IndexOutOfBoundsException
。
我想将它包装到一个迭代器中,以便能够编写更清晰的代码。但是,我需要捕获异常以停止迭代:
static IEnumerable<object> Iterator( ExAPI api ) {
try {
for( int i = 0; true; ++i ) {
yield return api[i]; // will throw eventually
}
}
catch( IndexOutOfBoundsException ) {
// expected: end of iteration.
}
}
但是......
当与表达式一起使用时,yield return 语句不能出现在 catch 块或在 try 块中 一个或多个 catch 子句。了解更多 信息,请参阅异常处理 语句(C# 参考)。语句(C# 参考)。 (来自 msdn)
我怎样才能换行这个API?
I have a class with an API that allows me to ask for objects until it throws an IndexOutOfBoundsException
.
I want to wrap it into an iterator, to be able to write cleaner code. However, I need to catch the exception to stop iterating:
static IEnumerable<object> Iterator( ExAPI api ) {
try {
for( int i = 0; true; ++i ) {
yield return api[i]; // will throw eventually
}
}
catch( IndexOutOfBoundsException ) {
// expected: end of iteration.
}
}
But...
When used with expression, a yield
return statement cannot appear in a
catch block or in a try block that has
one or more catch clauses. For more
information, see Exception Handling
Statements (C# Reference).Statements (C# Reference).
(from the msdn)
How can I still wrap this api?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您只需将
yield return
语句移到try
块之外,如下所示:You simply need to move the
yield return
statement outside of thetry
block, like this:您可以将获取对象的简单操作包装到一个单独的函数中。您可以在那里捕获异常:
然后,调用该函数并在必要时终止:
You can wrap the simple operation of getting the object into a separate function. You can catch the exception in there:
Then, call that function and terminate if necessary:
只需重新排序代码:
Just reorder the code:
如果您根本无法检查对象的边界,您可以执行类似的操作,
尽管现在我正在看这里,我相信上面的答案更好。 SLAks 发布的一张。
If you can't check the bounds of the object at all, you could do something like this
although now that im looking here, the answer above is better i believe. The one SLaks posted.