C# 行动<&燃气轮机;多参数语法澄清

C# 行动<&燃气轮机;多参数语法澄清,c#,action,notifyicon,C#,Action,Notifyicon,有时候我不能理解最简单的事情,我敢肯定那是在我的脸上,我只是看不见而已。 我正在尝试为此简单类中的方法创建委托: public static class BalloonTip { public static BalloonType BalType { get; set; } public static void ShowBalloon(string message, BalloonType bType) {

有时候我不能理解最简单的事情,我敢肯定那是在我的脸上,我只是看不见而已。 我正在尝试为此简单类中的方法创建委托:

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

    public static void ShowBalloon(string message, BalloonType bType)
    {
        // notify user
    }
}
现在,这个操作应该是创建委托,而不是实际使用关键字“delegate”声明一个委托,我理解正确了吗?然后:

private void NotifyUser(string message, BalloonTip.BalloonType ballType)
    {
        Action<string, BalloonTip.BalloonType> act; 
        act((message, ballType) => BalloonTip.ShowBalloon(message,  ballType));
    }
private void NotifyUser(字符串消息,balloottip.balloottype)
{
行动法;
act((message,ballType)=>balloottip.ShowBalloon(message,ballType));
}
这无法编译。为什么?

(顺便说一句,我之所以需要这个委托而不是直接调用ShowBalloon(),是因为调用必须从UI线程以外的其他线程进行,所以我想我需要这个操作)


谢谢,

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

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

    act(message, ballType);
}

您不应该为
act
变量赋值吗?类似于:

Action<string, BalloonTip.BalloonType> act = BalloonTip.ShowBalloon;
您还可以使其更简单:

public Action<string, BalloonTip.BalloonType> GetNotificationMethod() {
   return BalloonTip.ShowBalloon;
}  
公共操作GetNotificationMethod(){ 返回balloottip.ShowBalloon; }
希望我能理解你的问题。祝你好运。

操作没有什么特别之处,它只是.NET framework上“系统”命名空间中包含的一个通用委托(或一组更确切的Microsoft)。谢谢,我现在终于了解了此操作的工作原理和使用方法。
public Action<string, BalloonTip.BalloonType> GetNotificationMethod() {
   Action<string, BalloonTip.BalloonType> act = BalloonTip.ShowBalloon;
   return act;
}  
public Action<string, BalloonTip.BalloonType> GetNotificationMethod() {
   return BalloonTip.ShowBalloon;
}