【问题标题】:How Do I Create a C# Lambda Expression Programmatically?如何以编程方式创建 C# Lambda 表达式?
【发布时间】:2020-10-28 15:50:53
【问题描述】:

在这个例子中:

    class Example
    {
        public Example()
        {
            DoSomething(() => Callback);                  
        }

        void DoSomething(Expression<Func<Action<string>>> expression) {  }
        void Callback(string s) { }
    }

如果我有它的 MethodInfo,我如何以编程方式创建 () =&gt; Callback。调试器显示为:

{() => Convert(Void Callback(System.String).CreateDelegate(System.Action`1[System.String], value(Example)), Action`1)}

我在Expression.ConvertExpression.Lambda 中尝试了Expression.Call,但我无法正确获取委托部分。

【问题讨论】:

    标签: c# .net linq lambda


    【解决方案1】:

    你可以这样做:

    // obtain Example.Callback method info
    var callbackMethod = this.GetType().GetMethod("Callback", BindingFlags.Instance | BindingFlags.NonPublic);
    // obtain Delegate.CreateDelegate _instance_ method which accepts as argument type of delegate and target object
    var createDelegateMethod = typeof(MethodInfo).GetMethods(BindingFlags.Instance | BindingFlags.Public).First(c => c.Name == "CreateDelegate" && c.GetParameters().Length == 2);
    // create expression - call callbackMethod.CreateDelegate(typeof(Action<string>), this)
    var createDelegateExp = Expression.Call(Expression.Constant(callbackMethod), createDelegateMethod, Expression.Constant(typeof(Action<string>)), Expression.Constant(this));
    // the return type of previous expression is Delegate, but we need Action<string>, so convert
    var convert = Expression.Convert(createDelegateExp, typeof(Action<string>));
    var result = Expression.Lambda<Func<Action<string>>>(convert);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 2013-11-04
      • 2015-12-05
      • 2011-05-05
      • 1970-01-01
      相关资源
      最近更新 更多