0

我想创建一个能够使用我在 Vector 类(MathNet)上创建的多个扩展的方法。例如,我有 Vector 扩展:

public static bool IsNaN(this  Vector<double> m)
    {
        int i = Array.IndexOf(m.ToArray(), double.NaN);
        bool b = (i == -1);
        b = !b;
        return b;
    }

我希望能够将此扩展用作参数。例如,我想写一些类似的东西:

         public static Vector<double> ApplyExtension(this Matrix<double> x, VectorExtension myOperation)
    {
        Vector<double> res = new DenseVector(x.ColumnCount, 0);
        for (int i = 0; i < x.ColumnCount; i++)
        {
            res[i] = x.Row(i).myOperation();
        }
        return res;
    }

当然,“VectorExtension”不是一个定义明确的类型。我试图创建一个代表:

public delegate double VectorExtension(this Vector<double> d);

但是,它不起作用。有人可以帮助我吗?非常感谢!

4

2 回答 2

2
public static Vector<TResult> ApplyExtension<T, TResult>(this Matrix<T> x, Func<Vector<T>, TResult> myOperation)
{
   var res = new DenseVector(x.ColumnCount, 0);
   for (int i = 0; i < x.ColumnCount; i++)
   {
       res[i] = myOperation(x.Row(i));
   }
   return res;
}

现在您可以使用方法组语法

matrix.ApplyExtension(VectorExtensions.IsNaN);

或将 cal 包装到另一个 lambda

matrix.ApplyExtension(vector => vector.IsNaN());
于 2013-05-29T14:34:49.753 回答
0

委托不需要知道或关心提供给它的方法是扩展方法。您也无法将提供给它的方法强制为扩展方法。

扩展方法实际上只是另一种静态方法;相应地踩它:

public static Vector<double> Apply(this Matrix<double> x
    , Func<Vector<double>, double> myOperation)
{ }

然后你会这样称呼它:

myMatrix.Apply(VectorExtensions.SomeOperation);
于 2013-05-29T14:34:51.053 回答