Action <>多参数语法澄清

Amc*_*tty 6 c# action notifyicon

有时我无法理解最简单的事情,我确信这是在我的脸上,我只是没有看到它.我试图在这个简单的类中为方法创建一个委托:

public static class BalloonTip
{
    public static BalloonType BalType
    { 
        get; 
        set; 
    }

    public static void ShowBalloon(string message, BalloonType bType)
    {
        // notify user
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,这个Action <>应该创建委托而不实际声明一个关键字"委托",我是否理解正确?然后:

private void NotifyUser(string message, BalloonTip.BalloonType ballType)
    {
        Action<string, BalloonTip.BalloonType> act; 
        act((message, ballType) => BalloonTip.ShowBalloon(message,  ballType));
    }
Run Code Online (Sandbox Code Playgroud)

这无法编译.为什么?

(顺便说一句,我需要这个委托而不是直接调用ShowBalloon()的原因是,调用必须来自另一个线程而不是UI,所以我想我需要Action <>)

谢谢,

Dou*_*las 10

您需要先将匿名方法分配给Action变量,然后使用传入方法的参数调用它:

private void NotifyUser(string message, BalloonTip.BalloonType ballType)
{
    Action<string, BalloonTip.BalloonType> act = 
        (m, b) => BalloonTip.ShowBalloon(m, b);

    act(message, ballType);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,由于变量所期望的参数Action与封装方法的参数相同,因此您也可以直接引用该方法:

private void NotifyUser(string message, BalloonTip.BalloonType ballType)
{
    Action<string, BalloonTip.BalloonType> act = BalloonTip.ShowBalloon;

    act(message, ballType);
}
Run Code Online (Sandbox Code Playgroud)