C# 我应该如何创建回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/716274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:17:11  来源:igfitidea点击:

How should i create a callback

c#callback

提问by

What is the best way to write a callback? I only need to call 1 function that has the sig of void (string, int); and this would need to invoke a class since i have member objs that i need to process. Whats the best way to write this? in C i would do pass a func pointer and an void*obj. i dislike that and i suspect there is a better way to do this in C#?

编写回调的最佳方法是什么?我只需要调用 1 个具有 void (string, int) 信号的函数;这将需要调用一个类,因为我有需要处理的成员对象。写这个最好的方法是什么?在 C 中,我会传递一个 func 指针和一个 void*obj。我不喜欢那样,我怀疑在 C# 中有更好的方法来做到这一点?

采纳答案by Reed Copsey

The standard way of handling (or replacing the need for) callbacks in C# is to use delegates or events. See this tutorial for details.

在 C# 中处理(或替换需要)回调的标准方法是使用委托或事件。 有关详细信息,请参阅本教程。

This provides a very powerful, clean way of handling callbacks.

这提供了一种非常强大、干净的回调处理方式。

回答by Samuel

C#3.0 introduced lambdas which allow you forgo the declaration of callback (or delegate) signatures. It allows you to do things like:

C#3.0 引入了 lambdas,它允许您放弃回调(或委托)签名的声明。它允许您执行以下操作:

static void GiveMeTheDate(Action<int, string> action)
{
  var now = DateTime.Now;
  action(now.Day, now.ToString("MMMM"));
}

GiveMeTheDate((day, month) => Console.WriteLine("Day: {0}, Month: {1}", day, month));
// prints "Day: 3, Month: April"

回答by bytebender

Is this what you mean?

你是这个意思吗?

thatfunc(params, it, wants, Func<myObject> myCallbackFunc)
{
    myObject obj = new Object(); 

    myCallbackFunc.Invoke(obj);

//or

    myCallbackFunc.Invoke(this);

//I wasn't sure what if myObject contained thatFunc or not...
}