C# 如何使用 Lambda 表达式将带有两个参数的操作传递给方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2050322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:00:41  来源:igfitidea点击:

How to pass action with two parameters using Lambda expression to method?

c#silverlightlambda

提问by Chris

I have a class that takes an action in it's constructor.

我有一个在其构造函数中执行操作的类。

Example:

例子:

public CustomClass(Action<Path> insert)
{

  // logic here...

}

I currently instantiate this class using the following line of code:

我目前使用以下代码行实例化此类:

var custom = new CustomClass((o) => LayoutRoot.Children.Add(o));

I want to modify the custom class to include an additional constructor, such as the following:

我想修改自定义类以包含一个额外的构造函数,例如:

public CustomClass(Action<Path, TextBlock> insert)
{

  // logic here...

}

However, my knowledge of lambda expressions is pretty basic, so I can't figure out how to instantiate the custom class, passing two parameters in the action to the new constructor.

但是,我对 lambda 表达式的了解非常基础,所以我无法弄清楚如何实例化自定义类,将操作中的两个参数传递给新的构造函数。

Any help would be greatly appreciated.

任何帮助将不胜感激。

Thanks.

谢谢。

采纳答案by Francisco Noriega

In order to pass 2 parameters to the action, just define the insert action as an Action<T,T2>and when you call it do it like this:

为了将 2 个参数传递给操作,只需将插入操作定义为 an Action<T,T2>,当您调用它时,请执行以下操作:

var custom = new CustomClass((o,u) => {LayoutRoot.Children.Add(o); somethingElse(u)});

回答by Tony The Lion

In Lamba you can pass two parameters as such:

在 Lamba 中,您可以像这样传递两个参数:

(x, y) => { x.DoSomething(); y.DoSomethingElse(); }

回答by Stan R.

Either you are asking

要么你问

public CustomClass(Action insert, Action insert2) { // logic here... }

or

或者

 public CustomClass(Action<T1, T2> insert) { // logic here... }

The second constructor will take an delegate that receives 2 parameters. So you can do something like

第二个构造函数将接受一个接收 2 个参数的委托。所以你可以做类似的事情

CustomClass class = new CustomClass( (x,y) => DoSomething(x,y) );

回答by LBushkin

You can create a lambda expression that takes more than one parameter by surrounding the parameter list with parentheses and comma separate the parameters:

您可以创建一个接受多个参数的 lambda 表达式,方法是用括号将参数列表括起来,并用逗号分隔参数:

var custom = new CustomClass((o, tb) => /* use both params somehow */ );

If you need to perform more than one statement in a lambda, you can surround the body of the lambda with braces:

如果需要在 lambda 中执行多个语句,可以用大括号将 lambda 的主体括起来:

var custom = new CustomClass((o, tb) => { o.DoSomething(); tb.DoSomethingElse() } );

You can learn more about lambda syntax here on MSDN.

您可以在 MSDN 上了解有关lambda 语法的更多信息。