动作<>多参数语法说明 [英] Action<> multiple parameters syntax clarification
问题描述
有时候我听不懂最简单的东西,我确定它在我的脸上,只是看不到它。
我试图在此简单类中为方法创建委托:
Sometimes I can't understand the simplest things, i'm sure it's in my face, i just fail to see it. Im trying to create a delegate for a method in this simple class:
public static class BalloonTip
{
public static BalloonType BalType
{
get;
set;
}
public static void ShowBalloon(string message, BalloonType bType)
{
// notify user
}
}
现在,此Action<>应该创建委托而不实际使用关键字 delegate声明一个委托,我理解正确吗?然后:
Now, this Action<> is supposed to create the delegate without actually declaring one with the keyword "delegate", did I understand correctly? Then:
private void NotifyUser(string message, BalloonTip.BalloonType ballType)
{
Action<string, BalloonTip.BalloonType> act;
act((message, ballType) => BalloonTip.ShowBalloon(message, ballType));
}
此操作无法编译。为什么?
This fails to compile. Why?
(顺便说一句,我之所以需要此委托而不是直接调用ShowBalloon()的原因是,这些调用必须从不同于UI的另一个线程进行,所以我想我需要Action<>)
(By the way, the reason why I need this delegate instead of directly calling ShowBalloon(), is that the calls must be made from another thread than the UI one, so I figured I need the Action<>)
谢谢
推荐答案
您需要先将匿名方法分配给 Action
变量,然后使用传递给方法的参数调用它:
You need to first assign your anonymous method to the Action
variable, then invoke it with the arguments passed in to the method:
private void NotifyUser(string message, BalloonTip.BalloonType ballType)
{
Action<string, BalloonTip.BalloonType> act =
(m, b) => BalloonTip.ShowBalloon(m, b);
act(message, ballType);
}
在这种情况下,由于您的期望的参数操作
变量与封装方法的变量相同,您也可以直接引用该方法:
In this case, since the arguments expected by your Action
variable are identical to those of the encapsulated method, you may also reference the method directly:
private void NotifyUser(string message, BalloonTip.BalloonType ballType)
{
Action<string, BalloonTip.BalloonType> act = BalloonTip.ShowBalloon;
act(message, ballType);
}
这篇关于动作<>多参数语法说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!