Casting of Generic List to a Class derived from a List

前端 未结 5 2040
萌比男神i
萌比男神i 2020-12-11 17:33

I created a class derived from List. However when I tried casting the class to another List object I get a runtime error. My code is similar to the one posted below:

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 17:56

    You can use this Extension Method

    public static M Cast(this IEnumerable input) where M : ICollection, new()
    {
      var ret = new M();
      foreach(var item in input?? Enumerable.Empty())
      {
        ret.Add(item);
      }
      return ret;
    }
    

    then you can use it like

    var qry = (from c in db.Categories
       select new CategoryObj
       {
           CategoryID = c.CategoryID,
           CategoryName = c.CategoryName,
           Description = c.Description
        }).Cast()
    

提交回复
热议问题