使用Expression.Call创建Matrix <t> .Build.Dense()

时间:2017-06-21 15:07:55

标签: c# matrix mathnet

我想返回一个创建密集MathNet矩阵的Expression.Call。

这是我想要的矩阵:

Matrix<ContentType>.Build.Dense(Rows,Columns)

ContentType将为intdoubleComplex

但我想用Expression.Call创建它。 这是我目前的代码:

Expression.Call(
            typeof(Matrix<>)
                .MakeGenericType(ContentType)
                .GetProperty("Build")
                .GetMethod("Dense", new[] {typeof(int), typeof(int)}),
            Expression.Constant(Rows), Expression.Constant(Columns));

然而,这会导致构建错误:

[CS1955] Non-invocable member 'PropertyInfo.GetMethod' cannot be used like a method.

我做错了什么?

1 个答案:

答案 0 :(得分:1)

GetMethod类型上有PropertyInfo 属性,它返回属性getter方法。您正在尝试将此属性用作方法(调用它) - 因此编译器错误。相反,你应该这样做:

// first get Build static field (it's not a property by the way)
var buildProp = typeof(Matrix<>).MakeGenericType(ContentType)
               .GetField("Build", BindingFlags.Public | BindingFlags.Static);
// then get Dense method reference
var dense = typeof(MatrixBuilder<>).MakeGenericType(ContentType)
               .GetMethod("Dense", new[] { typeof(int), typeof(int) });
// now construct expression call
var call = Expression.Call(
               Expression.Field(null /* because static */, buildProp), 
               dense, 
               Expression.Constant(Rows), 
               Expression.Constant(Columns));