【问题标题】:Parameterized Action Invoke Delegate参数化动作调用委托
【发布时间】:2023-04-04 13:45:01
【问题描述】:

我有以下工作代码示例:

public void ClearLogText() => this.TxtLog.Invoke((Action)delegate {this.TxtLog.Text = string.Empty;});

如何正确添加参数?

public void SetControlText(Control control, string text) => this.Invoke((Action<Control, string>delegate (Control x, string y) {x.Text = y;});

我遇到的问题是如何在函数中使用参数,在本例中为controltext

注意:方法可以是任何东西。我关心的是概念,而不是方法的作用。这只是我想到的第一件事。

Visual Studio 抱怨很明显,即我没有在方法中使用参数。

我已经知道如何使用Actions,例如this 的回答。让我失望的是Invokedelegate 部分。

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

    act(message, ballType);
}

我还想使用构造 this.X.Invoke((Action)delegate... 将答案保留在一行,因此这个问题,否则答案将是:

    public delegate void DelegateSetControlText(Control control, string text);

    public void SetControlText(Control control, string text)
    {
        if (true == this.InvokeRequired)
        {
            Program.DelegateSetControlText d = new Program.DelegateSetControlText(this.SetControlText);
            this.Invoke(d, new object[] { control, text });
        }
        else
            control.Text = text;
    }

【问题讨论】:

  • this.Invoke(delegate (Control x, string y) {x.Text = y;}, new object[] {control, text}); 怎么样?
  • @juharr 抛出Error CS1660 Cannot convert anonymous method to type 'Delegate' because it is not a delegate type。在一家公司的顶级程序员向我展示了短版本之前,我一直使用长方法。他提到Action 的事情是必要的。我喜欢声明的简单性甚至可读性。我想通过添加参数来扩展它,只是我遗漏了一些明显的东西。

标签: c# winforms delegates action invoke


【解决方案1】:

没有必要在实际调用中包含 delegate 演员表。
参数进入Invoke方法的第二个参数,是一个params对象数组,这里包含controltext

public void SetControlText(Control control, string text)
    => this.Invoke((Action<Control, string>)((ctrl, txt) => ctrl.Text = txt), control, text);

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多