explicit conversion operator error when converting generic lists

后端 未结 2 499
难免孤独
难免孤独 2020-11-30 15:07

I am creating an explicit conversion operator to convert between a generic list of entity types to a generic list of model types. Does anyone know why I get the following e

2条回答
  •  借酒劲吻你
    2020-11-30 15:42

    Basically, you can't do this. In your operator either the input or output type must be of the type that declares the operator. One option might be an extension method, but to be honest LINQ Select comes pretty close by itself, as does List.ConvertAll.

    As an example of the extension method approach:

    public static class MyListUtils {
      public static List ToModel(this List entities)
      {
        return entities.ConvertAll(entity => (Model.objA)entity);
      }
    }
    

    or more generally with LINQ Select:

    public static class MyListUtils {
      public static IEnumerable ToModel(
         this IEnumerable entities)
      {
        return entities.Select(entity => (Model.objA)entity);
      }
    }
    

    and just use someList.ToModel().

提交回复
热议问题