Reputation: 154
I have the following classes:
public class A {
public C mObj:
}
public class B : A {
}
public class C {
public int val1;
}
public class D : C {
public int val2;
}
I initialize all the class B instances in a way that inst.mObj = new D();
. When I have an instance of class B I would ideally like to access all the members of class D by using mObj
, but due to inheritance I can not do it without casting into D first.
I would like class B to have a member object of class D, but I automatically inherit a member from class C. Is there a way to achieve something like that? If not then how is it usually done when a similar structure is required?
Upvotes: 0
Views: 54
Reputation: 10401
It is difficult to determine your exact requirements, but you could try to use generics with type constraints:
public class A<T>
where T : C
{
public T mObj:
}
public class B : A<D>
{
}
public class C
{
public int val1;
}
public class D : C
{
public int val2;
}
In this case the mObj
in B
will be of type D
, so no conversion will be required.
Upvotes: 4