Yield Return with Null

前端 未结 6 1750
长发绾君心
长发绾君心 2020-12-16 09:52

Is there any way to optionally return a null with a \"return yield\" driven iterator?

I would like to return a null in some cases and I don\'t think this is particul

6条回答
  •  离开以前
    2020-12-16 10:39

    There is no way to return a null IEnumerable from within an iterator method. You can return null values in the iterator but not a null IEnumerable

    What you could do though is have a wrapper method which either returns null or calls to the real iterator

    static IEnumerable GetItems() {
        if (false) {
            return GetItemsCore();
        }
        return null;
    }
    
    static IEnumerable GetItemsCore() {
        yield return "Andy";
        yield return "Jennifer";
    }
    

提交回复
热议问题