我有以下代码:

virtual public IEnumerable<string> GetSelectedIds(){
   if (_kids == null)
        yield return null;
   foreach (var current in _kids.Nodes)
        yield return current;
}


如果_kids.Nodes,这段代码在NullPointerException处以_kids == null崩溃

如果_kids == null,我希望此方法在前提条件级别返回,但事实并非如此!



为什么方法开头的前提没有效果?

最佳答案

更改

if (_kids == null)
        yield return null;




if (_kids == null)
        yield break;


这将返回一个空序列,用户将不必检查返回值。

或者你可以重写为

public IEnumerable<string> GetSelectedIds(){
   if (_kids == null)
        return null;

   return GetSelectedIds2();
}

private IEnumerable<string> GetSelectedIds2()
{
    foreach (var current in _kids.Nodes)
        yield return current;
}

关于c# - yield 怪异行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20214815/

10-16 05:18
查看更多