Is yield useful outside of LINQ?

后端 未结 14 920
野性不改
野性不改 2020-12-24 06:44

When ever I think I can use the yield keyword, I take a step back and look at how it will impact my project. I always end up returning a collection instead of yeilding becau

14条回答
  •  伪装坚强ぢ
    2020-12-24 07:41

    Whenever your function returns IEnumerable you should use "yielding". Not in .Net > 3.0 only.

    .Net 2.0 example:

      public static class FuncUtils
      {
          public delegate T Func();
          public delegate T Func(A0 arg0);
          public delegate T Func(A0 arg0, A1 arg1);
          ... 
    
          public static IEnumerable Filter(IEnumerable e, Func filterFunc)
          {
              foreach (T el in e)
                  if (filterFunc(el)) 
                      yield return el;
          }
    
    
          public static IEnumerable Map(IEnumerable e, Func mapFunc)
          {
              foreach (T el in e) 
                  yield return mapFunc(el);
          }
            ...
    

提交回复
热议问题