【问题标题】:C# pass callback to button [duplicate]C#将回调传递给按钮[重复]
【发布时间】:2015-05-17 20:44:39
【问题描述】:

在 Javascript 或 Flash 中,我习惯于将回调传递给我的按钮对象,如下所示:

主类

function init() {
   var myButton = new Button("red", doSomething);
}
function doSomething() {
    log("someone clicked our button, but who?");
}

按钮类构造函数

function Button(color, callback) {
     addListener(mouseClick, callback);
}

这个例子大大简化了,重点是可以将函数名作为参数传递给Button实例。按钮一旦被点击就会调用该函数。

这在 C# 中可行吗?我读过一些关于代表的东西,但想不出一个简单的例子。

【问题讨论】:

    标签: c# xna


    【解决方案1】:

    很简单:

    //Declare the function "interface"
    delegate string UppercaseDelegate(string input);
    //Declare the function to be passed
    static string UppercaseAll(string input)
    {
    return input.ToUpper();
    }
    //Declare the methode the accepts the delegate
    static void WriteOutput(string input, UppercaseDelegate del)
    {
        Console.WriteLine("Before: {0}", input);
        Console.WriteLine("After: {0}", del(input));
    }
    
    static void Main()
    {
    WriteOutput("test sentence", new UppercaseDelegate(UppercaseAll));
    }
    

    【讨论】:

      【解决方案2】:

      似乎没有办法使用 WinForms 中的 Button 类在构造函数中分配回调。但作为第二步,这相当容易:

      Button myButton = new Button("Text Displayed");
      myButton.Click += (sender, args) => SomeFunction();
      

      【讨论】:

        猜你喜欢
        • 2018-03-01
        • 2017-01-18
        • 1970-01-01
        • 1970-01-01
        • 2019-04-03
        • 1970-01-01
        • 1970-01-01
        • 2015-07-27
        • 1970-01-01
        相关资源
        最近更新 更多