I have a scenario where I am working with a library from another department in my company that I cannot just change (otherwise it could cause problems later when they release upgrades), and I'm trying to figure out a way to work with some of their types. Basically, they have the following classes:
public class Food
{
... properties that apply to all food ...
}
public class Pie : Food
public class Grapefruit : Food
{
public int NumberOfSeeds = 50;
}
public class Cherry : Food
{
public int NumberOfSeeds = 1;
}
Now, "Grapefruit" and "Cherry" both have the "NumberOfSeeds" property, but that property is not part of the Food class.
I'm working on a "helper" class that removes seeds, so I'm trying to do something like this:
public class FoodHelper
{
public Food item;
public void RemoveSeeds()
{
item.NumberOfSeeds = 0;
}
}
public class GrapefruitHelper : FoodHelper
{
new public Grapefruit item;
}
public class CherryHelper : FoodHelper
{
new public Cherry item;
}
I'm trying to avoid having to redefine "RemoveSeeds" over and over again in the child classes (the real method is pretty monstrous), but when I define it in the parent class, I get a warning that "Food" doesn't contain the "NumberOfSeeds"
property, which is correct.
Also, if I try to use any valid type like "Cherry" instead of "Food" in the parent class in order to make the RemoveSeeds work, then I'm forced to override / hide the "item" in the child classes and the parent methods don't even
see the right "item".
I've experimented with trying to use dynamic <T> types in my class definitions, but with no luck. I would also rather avoid using Reflection if possible. Ideally, I would like to create a new Fruit "group" type and be able to specify Grapefruit
and Cherry as members of that group, and then use Fruit as a type of base class parameter, like this:
public class FoodHelper { public Fruit item; // Somehow Grapefruit and Cherry are identified as Fruit public void RemoveSeeds() { item.NumberOfSeeds = 0; } } public class GrapefruitHelper : FoodHelper {
...any Grapefruit-specific code...
}
public class CherryHelper : FoodHelper {
...any Cherry-specific code...
}
Can anyone point me in the right direction here?