我正在使用 MiscUtils 库(感谢 Marc G. 和 Jon S.)并试图向Sqrt它添加一个通用函数。这个问题可以很容易地重现:
class N<T>
{
    public N(T value)
    {
        Value = value;
    }
    public readonly T Value;
    public static implicit operator T(N<T> n)
    {
        return n.Value;
    }
    public static implicit operator N<T>(T value)
    {
        return new N<T>(value);
    }
    public static T operator /(N<T> lhs, T rhs)
    {
        // Operator.Divide is essentially a wrapper around 
        // System.Linq.Expressions.Expression.Divide
        return Operator.Divide(lhs.Value, rhs);
    }
}
// fails with: No coercion operator is defined 
// between types 'System.Double' and 'N`1[System.Single]'.
var n = new Numeric<float>(1f);
var x = Operator.DivideAlternative(n, 1.0);
// this works as the N<T> is first converted to a 
// float via the implicit conversion operator 
var result = n / 1.0;
现在,我意识到为什么会发生这种情况,但我还没有想出解决办法。作为参考,这里是当前的Sqrt实现。我几乎没有构建表达式树的经验。
public static double Sqrt<T>(T value)
{
    double oldGuess = -1;
    double guess = 1;
    while(Abs(guess - oldGuess) > 1)
    {
        oldGuess = guess;
        // the first evaluated call to DivideAlternative throws
        guess = Operator.Divide(
                    Operator.AddAlternative(guess, 
                        Operator.DivideAlternative(value, guess)),
                    2);
    }
    return guess;
}
编辑:好的,所以我自己解决了这个问题,但为了让问题尽可能简单,我显然走得太远了,花了太多时间回答困惑的人试图提供帮助的问题。
所以,这就是问题的全部。
我两班;一个执行转换,另一个执行图像数据(像素)的统计分析。让我们关注后者,因为问题是一样的:
abstract class ImageStatistics
{
    private readonly object _pixels;
    public ImageStatistics(object pixelArray)
    {
        Pixels = pixelArray;
    }
    // calculate the standard deviation of pixel values
    public double CalcStdDev();
}
像素数组可以是任何数字类型。在实践中,它将是float、int、ushort或byte。现在,因为泛型不能做这样的事情:
public T Add<T>(T lhs, T rhs)
{
    return lhs + rhs;  // oops, no operator + for T
}
如果不转换为正确的数组类型,我无法对像素值本身进行任何类型的统计分析。所以,我需要有 N 个子类ImageProcessor来支持 N 个像素类型。  
嗯,这很糟糕。我很想拥有一个具有像素数据的通用ImageProcessor<T>类。T[]因此,我查看了允许这样做的 MiscUtils 库。