C# 简单Func的生成表达式
我想为如下内容构建表达式:C# 简单Func的生成表达式,c#,lambda,expression,C#,Lambda,Expression,我想为如下内容构建表达式: x => DoSomething(x) using System; using System.Linq.Expressions; public class Program { public static void Main() { Expression<Func<string, string>> func = (x) => DoSomething(x); Console.Writ
x => DoSomething(x)
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
}
}
有可能吗?我怎样才能做到这一点?您可以这样做:
x => DoSomething(x)
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
}
}
使用系统;
使用System.Linq.Expressions;
公共课程
{
公共静态void Main()
{
表达式func=(x)=>DoSomething(x);
Console.WriteLine(funct.ToString());
}
公共静态字符串DoSomething(字符串s)
{
返回s;//与示例一样
}
}
这是工作小提琴-
它将被解析,Lambda将保存为表达式您是说Func
delegate吗
基本上你需要一个Func
Func Func=x=>DoSomething(x)
其中
x
属于Tin
类型和DoSomething
returnTout
type可能问题有点不清楚。这就是我的意思:
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
这就是我想要的。谢谢你的时间:)你在问什么语言?这不是一个表达。它将被编译为匿名方法,而不是表达式如果您不需要在运行时进行编译,并且您知道签名,那么您可以始终使用这样的代码
Expression func=(x)=>DoSomething(x)代码>因为它将生成与您的答案几乎相同的代码。是的,这只是一个更大(已经解决)问题的一小部分。我必须在运行时完成这一切。СПабСбб:)如果您感兴趣,这里是我一直在努力解决的完整问题:我明白了,是的,那么它是有意义的。不客气:)