I am struggling to cast in a tree hierarchy structure below is an example of the class hierarchy structure I would really appreciate if someone can point me in the right direction.
I am unable to cast
var myobj2 = (IR<JB>)JR;
Classes:
public class BASEA{ }
public class B: BASEA{ }
public class C: B{ }
public interface IR<T> { }
public abstract class JR<T> : IR<T> where T : B
{ public abstract void SetRule(); }
public class Action: JB<C>
{
public override void SetRule()
{
//Logic
}
}
public static class RuleLib
{
public static void ApplyTest<T>(T obj, IR<T> JB) where T:B
{
var myobj2 = (IR<JB>)JR; //=> does not cast!
}
}
public class Test
{
[Test]
public void demo()
{
var obj = new B();
var action = new Action();
RuleLib.ApplyRule(obj,action);
}
}
For this to work, your
IRule
interface needs to be covariant. The example given here shows the following covariance:This is basically exactly what you're doing. So in your code all you need to do is write
instead of
This makes it so that you can cast from an
IRule<U>
toIRule<V>
whereU
is a subclass ofV
(e.g. casting fromIRule<ShiftAction>
toIRule<Job>
).