我有一个带有 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.
}
}
But...
当与表达式一起使用时,yield
return 语句不能出现在
catch 块或在 try 块中
一个或多个 catch 子句。了解更多
信息,请参阅异常处理
语句(C# 参考)。语句(C# 参考)。
(来自msdn http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx)
我怎样才能仍然封装这个 api?
您只需移动yield return
声明之外的try
块,像这样:
static IEnumerable<object> Iterator( ExAPI api ) {
for( int i = 0; true; ++i ) {
object current;
try {
current = api[i];
} catch(IndexOutOfBoundsException) { yield break; }
yield return current;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)