C # Pass an object to a base class list

I have the following class structure:

public class Fruit { } public class Apple : Fruit { } 

And then I use the method from the .net structure, which gets me the property value from the class returned as an object. So,

 // values will be of type List<Apple> object values = someObject.GetValue() 

Now I have this object of values ​​of type List, and I want to pass it to a list of type Fruit. I tried the following, but that did not work.

 List<Fruit> fruits = values as List<Fruit>; 

Does anyone know how to move an object to a list of its base class?

Update: at the time of casting, I do not know that the value object is of type List. I just know that this should be a list of the type that inherits from Fruit.

+4
source share
3 answers

The problem is that List<Apple> and List<Fruit> are not co-options. First you need to click on List<Apple> , and then use the LINQ Cast method to add items to Fruit :

 List<Fruit> fruits = values is List<Apple> ? (values as List<Apple>).Cast<Fruit>().ToList() : new List<Fruit>(); 

If you don't know the type ahead of time and you don't need to change the list (and you are using C # 4.0), you can try:

 IEnumerable<Fruit> fruits = values as IEnumerable<Fruit>; 

Or, I think if you need a List:

 List<Fruit> fruits = (values as IEnumerable<Fruit>).ToList(); 
+5
source

you should try the linq linking method . Cast method will return IEnumerable of the type that you use for ...

  List<Fruit> fruits = null; if ( values is List<Apples> ) fruits = ((List<Apples>)values).Cast< fruits >.ToList(); 
+2
source

Since you say that you know that the object is a list of fruits, but you do not know which fruit it is a list of, you can do this:

 List<Fruit> fruits = ((IEnumerable)values).Cast<Fruit>().ToList(); 

If you are using .NET 4 (excluding Silverlight 4), you can use Justin Niessner's solution:

 List<Fruit> fruits = ((IEnumerable<Fruit>)values).ToList(); 

Finally, it may be possible to use a general solution if there is a call site where the static type of fetus is known (Apple or something else). That would mean changing the code quite a bit so that you no longer get the values ​​using reflection.

Another common approach would be to create a generic method and build it at runtime by calling GetType () on the object, but the treatment case is probably worse than the disease.

0
source

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


All Articles