Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 简单Func的生成表达式_C#_Lambda_Expression - Fatal编程技术网

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
return
Tout
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)因为它将生成与您的答案几乎相同的代码。是的,这只是一个更大(已经解决)问题的一小部分。我必须在运行时完成这一切。СПабСбб:)如果您感兴趣,这里是我一直在努力解决的完整问题:我明白了,是的,那么它是有意义的。不客气:)