简体   繁体   English

如何以编程方式创建 C# Lambda 表达式?

[英]How Do I Create a C# Lambda Expression Programmatically?

In this example:在这个例子中:

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

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

How do I create () => Callback programmatically, assuming I have its MethodInfo.我如何以编程方式创建() => Callback ,假设我有它的 MethodInfo。 The debugger shows it as:调试器将其显示为:

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

I tried an Expression.Call within an Expression.Convert within an Expression.Lambda , but I can't get the delegate part right.我在Expression.Call中的Expression.Convert尝试了一个Expression.Lambda ,但我无法正确获取委托部分。

You can do it like this:你可以这样做:

// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM