Casting generic classes in C #

I have a problem with a set of generic types.

For example, I have classes:

public class Dog
{
}

public class Husky : Dog
{

}

public class MyWrapper<T> where T : class
{
}

and then I want to do something like that, but I don’t know how

MyWrapper<Husky> husky = new MyWrapper<Husky>();
List<MyWrapper<Dog>> dogs= new List<MyWrapper<Dog>>();
dogs.Add(husky); // how to cast husky to MyWrapper<Dog>?

EDIT: changed Animal<T>to MyWrapper<T>, so this would be a more suitable example

+5
source share
5 answers

You can use common interface covariance in C # 4 or later. To do this, you will need to define a covariant interface (using out) and MyWrapperimplement this interface:

public class Dog 
{
}

public class Husky : Dog
{
}

public class MyWrapper<T> : IMyWrapper<T> where T : class
{
}

public interface IMyWrapper<out T> where T : class
{
}

Then you can do this:

var husky = new MyWrapper<Husky>();
var dogs = new List<IMyWrapper<Dog>>();
dogs.Add(husky);
+8
source

I am afraid that you cannot - although it Huskyis Dog, is Animal<Husky>not Animal<Dog>.

. .NET Casting Generic List .

+7

, ? , Animal .

public abstract class Animal
{
}

public class Dog : Animal
{
}

public class Husky : Dog 
{
}
+6

- -.

# :

  • .
  • .

: IAnimal<T>:

public class Dog
{
}

public class Husky : Dog
{

}

public interface IAnimal<out T>
    where T : class
{
}

public class Animal<T> : IAnimal<T> where T : class
{
}

:

        List<IAnimal<Dog>> list = new List<IAnimal<Dog>>();
        list.Add(new Animal<Husky>());

MSDN:

UPDATE

... T : class? , T - , , , ?

, ? , -: , Dog DERIVES Animal.

, .

, , , :

  • , , "B A"? = > .

  • , , "B A" = > .

, , .

+4

Animal<Husky> Animal<Dog>.

+2

All Articles