xto*_*ofl 7 .net c# exception yield-return
我有一个带有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.
}
}
Run Code Online (Sandbox Code Playgroud)
但...
与expression一起使用时,yield return语句不能出现在catch块或具有一个或多个catch子句的try块中.有关更多信息,请参阅异常处理语句(C#参考).Statements(C#参考).(来自msdn)
我怎么还可以包装这个api?
SLa*_*aks 14
您只需将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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1038 次 |
| 最近记录: |