开发者

Curious problem involving generics and static methods

开发者 https://www.devze.com 2023-01-09 11:34 出处:网络
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 coupl

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("DataMi开发者_StackOverflow中文版nimum");
        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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消