我想为这样的东西构建Expression:
x => DoSomething(x)
是否有可能,我该如何做到这一点?
答案 0 :(得分:1)
你可以这样做:
using System;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
Expression<Func<string, string>> func = (x) => DoSomething(x);
Console.WriteLine(func.ToString());
}
public static string DoSomething(string s)
{
return s; // just as sample
}
}
这是工作小提琴 - https://dotnetfiddle.net/j1YKpM 它将被解析,Lambda将保存为Expression
答案 1 :(得分:0)
您的意思是Func<Tin,Tout>
委托吗?
基本上你需要Func<Tin,Tout>
Func<Tin,Tout> func = x=> DoSomething(x)
x
类型为Tin
,DoSomething
返回Tout
类型
答案 2 :(得分:0)
也许这个问题有点不清楚。这就是我的意思:
var arg = Expression.Parameter(pluginType, "x");
var method = GetType().GetMethod("DoSomething");
var methodCall = Expression.Call(method, arg);
var lambda = Expression.Lambda(delegateType, methodCall, arg); // I was looking for this
这就是我想要的。谢谢你的时间:))