C# 通过函数传递参数<&燃气轮机;

C# 通过函数传递参数<&燃气轮机;,c#,delegates,func,C#,Delegates,Func,我使用带有lambda表达式的委托,而不是只包含一行代码的方法,如: Func<int, int, int> Add = (x, y) => x + y; int Result = Add(1, 2); // 3 您不能这样做,但您可以使用一种变通解决方案: 如果按以下方式定义函数: Func<string[], string> FuncArray = (listOfStrings) => { // Here you can work on the

我使用带有lambda表达式的委托,而不是只包含一行代码的方法,如:

Func<int, int, int> Add = (x, y) => x + y;
int Result = Add(1, 2); // 3

您不能这样做,但您可以使用一种变通解决方案:

如果按以下方式定义函数:

Func<string[], string> FuncArray = (listOfStrings) => 
{
    // Here you can work on the listOfStrings, process it... 
    // and finaly you return a string from this method... 
}
public void MyMethod(Func<string[], string> delegateMethod, params string[] listOfString)
{
    if (delegateMethod != null)
    {
        string value = delegateMethod(listOfStrings);
    }

}
Func FuncArray=(listofstring)=>
{
//在这里,您可以处理列表字符串,处理它。。。
//最后你从这个方法返回一个字符串。。。
}
之后,您可以通过以下方式在其他调用中使用该FuncArray:

Func<string[], string> FuncArray = (listOfStrings) => 
{
    // Here you can work on the listOfStrings, process it... 
    // and finaly you return a string from this method... 
}
public void MyMethod(Func<string[], string> delegateMethod, params string[] listOfString)
{
    if (delegateMethod != null)
    {
        string value = delegateMethod(listOfStrings);
    }

}
public void MyMethod(Func delegateMethod,params string[]listOfString)
{
if(delegateMethod!=null)
{
字符串值=delegateMethod(listOfStrings);
}
}

因此,您只需定义一个以字符串数组作为参数的Func,然后就可以从另一个具有“params string[]”参数的方法调用该Func

params
不是类型本身的一部分,因此不能指定
Func
。但是您可以声明自己的委托,这些委托类似于
Func
,但具有作为最终参数的参数数组。例如:

using System;

delegate TResult ParamsFunc<T, TResult>(params T[] arg);
delegate TResult ParamsFunc<T1, T2, TResult>(T1 arg1, params T2[] arg2);
delegate TResult ParamsFunc<T1, T2, T3, TResult>(T1 arg1, T2 arg2, params T3[] arg3);
// etc        

class Program
{
    static void Main(string[] args)
    {
        ParamsFunc<string, string, string> func =
            (format, values) => string.Format(format, string.Join("-", values));

        string result = func("Look here: {0}", "a", "b", "c");
        Console.WriteLine(result);
    }
}
使用系统;
委托TResult ParamsFunc(参数T[]arg);
委托TResult ParamsFunc(T1 arg1,参数T2[]arg2);
委托TResult ParamsFunc(T1 arg1、T2 arg2、参数T3[]arg3);
//等
班级计划
{
静态void Main(字符串[]参数)
{
参数函数=
(格式,值)=>string.format(格式,string.Join(“-”,值));
字符串result=func(“请看这里:{0}”,“a”,“b”,“c”);
控制台写入线(结果);
}
}

我不清楚您到底想做什么。我怀疑这个问题可以通过使用您自己的代理来解决,但是如果您可以提供更多信息,那么会更容易帮助您。在lambda本身中提到
params
关键字甚至是不合法的,即将箭头改为
(string format,params string[]values)=>string.format(format,string.Join(“-”,values));将不会编译。@JeppeStigNielsen:对-而且它成为lambda的一部分是没有意义的。不过,将其作为委托声明的一部分是非常有意义的。我想你是正确的。关键字被转换为参数上的
paramaryattribute
。这可以应用于生成的方法(将lambda转换为该方法),但不会有多大帮助。调用
func
(您的代码)时,我们不知道它包含什么方法。但是,如果我使用
ref
(我使用
(ref int x)=>{};
)创建一个lambda,并使用
out
创建另一个lambda,我会看到在编译器生成的方法上应用了。