views:

57

answers:

1

I have a number of data classes, which share an abstract base class so i can work with them generically (sort of). They each have a static method called Lerp, which i use frequently along with a couple of other lines. I wanted to refactor this out into a method because of DRY,but it seems there's no way to do so. How do i get around this?

Can provide code if neccessary.

The code is basically this:

        XmlNode mineDataMin = mineDataMaster.SelectSingleNode("DataMinimum");
        XmlNode mineDataMax = mineDataMaster.SelectSingleNode("DataMaximum");
        _mineTemplate = MineInfo.Lerp(
            new MineInfo(mineDataMin),
            new MineInfo(mineDataMax),
            _strength);

where the class MineInfo can be one of a few classes, that all share an abstract class which is used for being able to deal with any of them generically. Lerp is a static method, which is the source of the trouble.

+2  A: 

One way you can do this is to use delegation for your Lerp() function. It would be simplest if they all share the same signature.

e.g.,

public static Template CreateTemplate<T>( ... , Func<T, T, int, Template> lerp)
    where T : CommonClass
{
    XmlNode mineDataMin = mineDataMaster.SelectSingleNode("DataMinimum");
    XmlNode mineDataMax = mineDataMaster.SelectSingleNode("DataMaximum");
    return lerp(new T(mineDataMin), new T(mineDataMax), _strength);
}

_template = CreateTemplate( ... , MineInfo.Lerp);

Or if they don't have a common signature, use a delegate with the "largest common denominator" for a signature to call the actual lerp function.

_template = CreateTemplate( ... ,
    (min, max, strength) =>
    {
        return SomeOtherInfoInfo.Lerp(min, max); //doesn't use strength
    });

Otherwise there's always reflection.

Jeff M
Great idea! Thanks!
RCIX