Interface Type Return List

I have three classes that inherit from the same interface:

Apple:Resource Banana:Resource Orange:Resource 

I have another class, I have lists with type op each:

 private List<Apple> apples = new List<Banana>(); private List<Banana> bananas = new List<Empleado>(); private List<Orange> oranges = new List<Orange>(); 

Now I want a method that can return any of these lists, we can say something like the following:

 public List<Resource> getListOf(string resource) { switch (resource) { case "apple": return apples; break; case "bananas": return bananas; break; case "oranges": return oranges; break; default: Console.WriteLine("wrong fruit"); break; } } 

This gives me the following error:

It is not possible to implicitly convert the type ' System.Collections.Generic.List<Fruits.Apple> ' to System.Collections.Generic.List<Fruits.Resource>

I thought this would work the same as I can:

 foreach (Resource r in Fruitlist) { r.Meth(); } 
+4
source share
1 answer

A function that causes code to be interrupted due to its absence is called general type covariance. C # supports dispersion in generics , but only in interfaces (and not in specific classes).

The foreach snippet works because it treats Fruitlist as an IEnumerable<Fruit> , and since it is a common interface with a parameter of type out (covariant), the compiler can view it as an IEnumerable<Resource> .

If getListOf permissible for getListOf to return an IEnumerable<Resource> , then changing the signature of the function will compile the code. Otherwise, the compiler cannot guarantee type safety, because you can write this code:

 List<Resource> apples = this.getListOf("apple"); apples.Add(new Orange()); // adding a Resource to a List<Resource>, right? 

Another option is to return a non-generic type, in which case the type safety will be lost again, and the compiler will introduce runtime checks to make sure that you do not mix apples with oranges (but at least the code should work if it works well leads.)

+7
source

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


All Articles