通用线性插值器:如何应对DateTime?

5 c# generics

我想写一个LinearInterpolator类,其中X是X轴值的类型,Y是Y轴值的类型.我无法看到如何做到这一点,以便X可以是DateTime或double.该类如下所示(未经测试):

class LinearInterpolator<X, Y>
{
    private List<X> m_xAxis;
    private List<Y> m_yAxis;

    public LinearInterpolator(List<X> x, List<Y> y)
    {
        m_xAxis = x;
        m_yAxis = y;
    }

    public Y interpolate(X x)
    {
        int i = m_xAxis.BinarySearch(x);
        if (i >= 0)
        {
            return m_yAxis[i];
        }
        else
        {
            // Must interpolate.
            int rightIdx = ~i;
            if (rightIdx >= m_xAxis.Count)
                --rightIdx;
            int leftIdx = rightIdx - 1;

            X xRight = m_xAxis[rightIdx];
            X xLeft = m_xAxis[leftIdx];
            Y yRight = m_yAxis[rightIdx];
            Y yLeft = m_yAxis[leftIdx];

            // This is the expression I'd like to write generically.
            // I'd also like X to be compilable as a DateTime.
            Y y = yLeft + ((x - xLeft) / (xRight - xLeft)) * (yRight - yLeft);
            return y;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

它在C++中很容易,但我是C#泛型的新手,所以任何帮助都会受到赞赏.

spo*_*son 1

用作DateTime.Ticks插值。您可以使用long类型作为泛型来在时间之间进行插值。