List.Cast <> error "is a method that is not valid in this context"

I have an abstract parent class whose child classes inherit from it. I have another class that contains many List<> types for different child classes. Then I have a method in another class that takes a List<ParentType> parameter and just calls the methods declared abstract.

I am having a problem using List<T>.Cast<T2> in lists of child classes. I get an error message:

System.Linq.Enumerable.Cast (System.Collections.IEnumerable) 'is a method that is not valid in this context

Does anyone know how to fix this error? Or do I need to restore a list of type List<ParentType> and redo each element separately?

What I'm trying to do: a public abstract class P {public int num; public abstract double addSections (); }

 public class A : P { public int num2; public A(int r, int n) { num = r; num2 = n; } public double addSections() { return (double)num + (double)num2; } } public class B : P { public double g; public B(int r, double k) { num = r; g = k; } public double addSections() { return (double)num + g; } } public class MyClass { public MyClass() { List<A> listA; List<B> listB; //... helper(listA.Cast<P>()); //doesn't work helper(listB.Cast<P>().ToList()); //doesn't work either } public void helper(List<P> list) { //... } } 
+4
source share
2 answers

Instead of actually looking at the code so that we can fix it, how about changing the method:

 public void DoSomething<T>(IEnumerable<T> items) where T : ParentType { ... } 

Or, if you use C # 4 and .NET 4, this should be good, since IEnumerable<T> is covariant in T in .NET 4.

 public void DoSomething(IEnumerable<ParentType> items) { ... } 

Do you really need a method to accept a List<ParentType> ? In the end, if you are going to call:

 var parentList = childList.Cast<ParentType>().ToList(); 

and pass this to the method, then you have two completely separate lists at this point.

By the way, another effect of covariant IEnumerable<T> is that in .NET 4 you can avoid calling Cast and just call:

 var parentList = childList.ToList<ParentType>(); 

EDIT: now that you have posted your code, the only question is not to call the Cast method as a method:

 // This... helper(listB.Cast<P>.ToList()) // should be this: helper(listB.Cast<P>().ToList()) 
+7
source

Now that you have added the code, I see two potential problems:

  • You need to add parentheses when calling Cast for example.

    listA.Cast<P>()

    Cast not a special operator; it is an extension method, like everything else.

  • Are these helper calls at the class level and not inside another method? This will also be a problem.

+2
source

Source: https://habr.com/ru/post/1415451/


All Articles