Reputation: 830
Sorry for the bad title, finding it hard to narrow down what exactly this problem relates to.
I have two class hierarchies that are essentially built in parallel: for every subtype of BaseObject, there's a subtype of BaseUIObject. The specific reason for this is because BaseObjects are actually Scriptable Objects (unity), and so I'm using another set of classes to represent each instance of one of those scriptable objects.
Example code:
public abstract class BaseUIObject {
public BaseObject someObject;
public void Setup(BaseObject baseObject)
{ this.baseObject = baseObject; }
}
public class SomeUIObject : BaseUIObject {
public void Setup(SomeObject someObject)
{ base.Setup(someObject); SomeUIObjectSpecificRoutine(); }
private void SomeObjectSpecificRoutine() {
someObject.doSubClassFunction();
}
}
When passing the object of type SomeObject to the Setup of SomeUIObject, it becomes stored as a BaseObject instead of SomeObject. Is there any clean way to prevent this happening?
Right now the two options I have are either to define the someObject variable in every subclass of BaseUIObject, or to explicitly cast (SomeObject)someObject every time I use it in SomeUIObject's methods. Neither of these methods seem clean and I feel like there must be some nicer way of using inheritance to do this.
Thanks for any help.
Upvotes: 0
Views: 37
Reputation: 82474
Seems like a good place for Generics to me:
public abstract class BaseUIObject<T> where T : BaseObject
{
public T theObject { get; private set; }
public virtual void Setup(T baseObject)
{
this.theObject = baseObject;
}
}
And then, in your concrete UI objects:
public class SomeUIObject : BaseUIObject<SomeObject>
{
public override void Setup(SomeObject someObject)
{
base.Setup(someObject);
SomeUIObjectSpecificRoutine();
}
// rest of concrete class code...
}
Upvotes: 1