Throw between tribal collections

In the following example, why can't I drop collectionA in collectionB , given that the compiler knows that a TItem is A<T> ?

 public class A<T> { } public void Foo<TItem, T> () where TItem : A<T> { var collectionA = new List<TItem>(); var collectionB = (List<A<T>>)collectionA; // "Cannot cast" error here } 
+4
source share
3 answers

The problem is that it will allow you to put inappropriate items in the collection.

Here's a simplified recycling that hopefully makes the task easier:

Suppose you have (pseudocode):

 class Animal {...} class Dog: Animal { Bark(){} } class Cat: Animal { Meow(){} } 

Now imagine that you could do this:

 var dogs = new List<Dog>(); dogs.Add(new Dog()); dogs[0].Bark(); var animals = (List<Animal>) dogs; 

Then you can do it:

 animals.Add(new Animal()); // Adds an Animal to the list 'dogs', which 'animals' references. dogs[1].Bark(); // dogs will now have two elements, but the second isn't a dog - // so calling Bark() will explode. 
+1
source

I believe because you instruct the system to convert from List<X> to List<Y> instead of saying that you want to drop every item in the list from X to Y

You can do this though:

 public class A<T> { } public void Foo<TItem, T>() where TItem : A<T> { var collectionA = new List<TItem>(); var collectionB = new List<A<T>>(collectionA.ToArray()); } 
0
source

Do you want to use

 var collectionB = collectionA.OfType<List<A<T>>>(); 

or

 var collectionB = collectionA.Cast<List<A<T>>>(); 

The first ignores everything that is not of type List<A<T>> and cannot be considered like it. The second will throw an exception if there is something in the list that cannot be converted.

0
source

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


All Articles