'Is there runtime polymorphism in C# combined with generics?
I have 2 classes that inherit from the same generic abstract class. Inheriting and implementing the methods with a type works fine, but I can't figure out how to do late binding with an instance of that abstract class.
internal class NormalField : GenericClass<List<List<int>>>
{
protected override List<List<int>> doSomethingWithTheField(List<List<int>> field)
{
throw new NotImplementedException();
}
public override List<int> getFieldRow(int row)
{
throw new NotImplementedException();
}
}
internal class ComplexField : GenericClass<List<List<ComplexCell>>>
{
protected override List<List<ComplexCell>> doSomethingWithTheField(List<List<ComplexCell>> field)
{
throw new NotImplementedException();
}
public override List<int> getFieldRow(int row)
{
throw new NotImplementedException();
}
}
public class ComplexCell
{
int field;
int? secondField;
}
public abstract class GenericClass<T>
{
public T Field;
protected abstract T doSomethingWithTheField(T field); //class uses this internally
public abstract List<int> getFieldRow(int row); //used by another object
}
Unfortunately I have to declare the type before compiling so I cant dynamically assign another instance of the abstract class to a property.
public class Program
{
public static void Main(string[] args)
{
// I have to specify the type for the interface here and can't assign a complexfield later
GenericClass instance = new NormalField(); //not possible
instance = new ComplexField();
instance.getFieldRow(2);
}
}
A possible solution I came up with would be to seperate the getFieldRow() method from the abstract class and create a new interface with only the getFieldRow() method. Since there are no generics involved this would work, but is there also a way to do this with a abstract class with generics?
Solution 1:[1]
GenericClass<List<List<int>>>
and
GenericClass<List<List<ComplexCell>>>
are not the same base class
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Johannes |
