【问题标题】:Getting error "Static method requires null instance, non-static method requires non-null instance." while trying to execute expression tree in C#收到错误“静态方法需要空实例,非静态方法需要非空实例。”尝试在 C# 中执行表达式树时
【发布时间】:2020-08-27 22:19:48
【问题描述】:

在 C# 中,我有一个类 MyNamespace.MyClass,并且在该类中定义了一个方法 MyMethod。我试图在MyObjectMyClass 类的一个实例)上调用此方法,但标题中出现错误。这是我的代码:

Expression.Lambda(Expression.Call(typeof(MyNamespace.MyClass).GetMethod("MyMethod"), Expression.Constant("MyParam"))).Compile().Method.Invoke(MyObject, null);

MyMethod 不是静态方法。我做错了什么?

【问题讨论】:

  • 向我们展示您的代码,否则我们无能为力。

标签: c# lambda expression expression-trees


【解决方案1】:

首先采用 MethodInfo 的 Expression.Call 的重载用于静态方法。你需要这个:Expression.Call,例如编译一个调用myObject.MyMethod("MyParam")的委托将是:

    var f = (Action)Expression.Lambda(Expression.Call(Expression.Constant(myObject), typeof(MyClass).GetMethod("MyMethod"),  Expression.Constant("MyParam"))).Compile();

    f();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    相关资源
    最近更新 更多