简体   繁体   中英

How to use polymorphism in generic classes

I want to know if this question is valid, my Code is as follow:

Generic class when i will use polymorphism:

public class Foo<T> where T : fatherClass
{
   public T FooMethod1()
   {
     //enter code here
   }

   public void FooMethod2(T value)
   {
     //enter code here
   }
}

Entities classes who father is fatherClass

public class childClass1 : fatherClass
{
   //Attributes
}

public class childClass2 : fatherClass
{
   //Attributes
}

Concrete class who father is the generic class (Foo)

public class FooIn1 : Foo<childClass1>
{ }

public class FooIn2 : Foo<childClass2>
{ }

Try code:

class Program()
{
   public static Main(string[] args)
   {
      Foo<fatherClass> util;
      util = new FooIn1();
      util = new FooIn2();
   }
}

Is possible to use inheritance in this case?

Is possible to use inheritance in this case?

No, it isn't. Covariance and contravariance isn't supported for classes. Imagine you had the following:

List<ParentClass> parents = new List<Child1>();
parents.Add(new Child2());

This wouldn't be type safe. For that same reason, you can't create a FooIn1 where ParentClass is expected.

You can't use parent type in generic defenition and then initialize it to a list with child generic type. Instead, you can create your generic list based on the parent type. Then you can put inside the list any member of its children types. When you enumerate the list you will have to check if the object is of which child type using the is operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM