Reputation: 1
I would like to create a method that is able to use several extension I created on a Vector class (MathNet). For instance, I've got the Vector extension:
public static bool IsNaN(this Vector<double> m)
{
int i = Array.IndexOf(m.ToArray(), double.NaN);
bool b = (i == -1);
b = !b;
return b;
}
I would like to be able to use this extension AS A PARAMETER. For instance, I would like to write something like:
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;
}
Of course, "VectorExtension" is not a well defined type. I tried to create a deleguate:
public delegate double VectorExtension(this Vector<double> d);
But, it doesn't work. Could someone help me? Thanks a lot!
Upvotes: 0
Views: 106
Reputation: 23626
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;
}
now you can use method group syntax
matrix.ApplyExtension(VectorExtensions.IsNaN);
or wrap cal into another lambda
matrix.ApplyExtension(vector => vector.IsNaN());
Upvotes: 2
Reputation: 203821
The delegate doesn't need to know or care that the method provided to it is an extension method. There is no way you can force the method provided to it to be an extension method either.
The extension method is, under the hood, just another static method; tread it accordingly:
public static Vector<double> Apply(this Matrix<double> x
, Func<Vector<double>, double> myOperation)
{ }
You would then call it like:
myMatrix.Apply(VectorExtensions.SomeOperation);
Upvotes: 0