- Home /
Question by
falantar14 · Apr 20, 2016 at 10:02 PM ·
inheritanceinterfaceabstractpolymorphism
Accessing interface in a derived class through the parent class
I'll start off by saying that by no means am I attached to this method, so if anyone has a better idea how to do what I'm trying to do, I would be happy to hear it.
I have an abstract class Thing. From it, I have several derived classes, let's say Car and Box. Both Car, and Box use the same interface, IHealth, which has a property called HP.
In another method, I want a parameter that accepts all classes that derive from Thing and implement IHealth.
public interface IHealth
{
int hp {get; set;}
}
public abstract class Thing
{
//stuff goes here
}
public abstract class Vehicle : Thing, IHealth
{
public abstract int hp {get; set;}
}
public class Car : Vehicle
{
public override int hp;
}
public class Box : Thing, IHealth
{
public int hp;
}
public class SomeClass
{
void FirstMethod()
{
//This method gets a Thing and passes it to the next method
SecondMethod( Thing aThing );
}
void SecondMethod( Thing aThing )
{
// This method receives the Thing and needs to check if the Thing is implementing
// the interface, and either return, or retrieve the interface property hp
}
}
I have tried using a generic method, but I don't think that would work since the type that is passed as a parameter must directly inherit the interface (so I wouldn't be able to pass Thing.
Comment