涉及泛型和静态方法的好奇问题 [英] Curious problem involving generics and static methods
问题描述
我有许多数据类,它们共享一个抽象基类,所以我可以一般地使用它们(有点)。他们每个人都有一个名为Lerp的静态方法,我经常使用它和其他几行。我想把这个重构成一个方法,因为DRY,但似乎没有办法这样做。如何解决这个问题?
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.
代码基本上是这样的:
XmlNode mineDataMin = mineDataMaster.SelectSingleNode("DataMinimum");
XmlNode mineDataMax = mineDataMaster.SelectSingleNode("DataMaximum");
_mineTemplate = MineInfo.Lerp(
new MineInfo(mineDataMin),
new MineInfo(mineDataMax),
_strength);
其中MineInfo类可以是几个类中的一个,它们都共享一个抽象类因为能够一般地处理它们中的任何一个。 Lerp是一种静态方法,它是麻烦的根源。
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.
推荐答案
你的 Lerp()
函数。如果他们都共享相同的签名,这将是最简单的。
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);
或者如果他们没有共同签名,请使用最大公分母
$ b
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
});
否则就会有反射。
这篇关于涉及泛型和静态方法的好奇问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!