【问题标题】:Creating a Matrix<T>.Build.Dense() using Expression.Call使用 Expression.Call 创建 Matrix<T>.Build.Dense()
【发布时间】:2017-06-21 15:07:54
【问题描述】:

我想返回一个创建密集 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.

我做错了什么?

【问题讨论】:

    标签: c# matrix mathnet-numerics


    【解决方案1】:

    PropertyInfo 类型上有GetMethod property,它返回属性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));
    

    【讨论】:

    • 有效!您能否向我解释一下:您是如何知道使用 MatrixBuilder 或 BindingFlags 的?有没有我没找到的文档?
    • MatrixBuilder 是Matrix.Build 字段的类型。所以它是包含 Dense 方法的 MatrixBuilder 类型。至于绑定标志 - 这只是一种常识,它们在使用反射的任何地方都使用。但是在这种特殊情况下,它们不是必需的,为了清楚起见,我总是使用它们。如果您只使用GetField("Build") - 将使用默认标志:BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public。由于我们需要公共静态字段 (Build) - 默认标志可以正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 2013-07-08
    • 2021-02-26
    • 1970-01-01
    相关资源
    最近更新 更多