C#中的回调 [英] Callbacks in C#
问题描述
我想要一个库,里面有一个函数,它接受一个对象作为它的参数.
I want to have a library that will have a function in it that accepts an object for it's parameter.
有了这个对象,我希望能够在 X 完成时调用指定的函数.将调用的函数由调用者指定,X由库完成和监控.
With this object I want to be able to call a specified function when X is finished. The function that will be called is to be specified by the caller, and X will be done and monitored by the library.
我该怎么做?
作为参考,我使用的是 C# 和 .NET 3.5
For reference I'm using C# and .NET 3.5
推荐答案
两个选项:
Have the function accept a delegate (
Action
for a callback that doesn't return anything,Func
for one that does) and use an anonymous delegate or Lambda Expression when calling it.
使用界面
使用委托/lambda
public static void DoWork(Action processAction)
{
// do work
if (processAction != null)
processAction();
}
public static void Main()
{
// using anonymous delegate
DoWork(delegate() { Console.WriteLine("Completed"); });
// using Lambda
DoWork(() => Console.WriteLine("Completed"));
}
如果你的回调需要传递一些东西,你可以在Action
上使用一个类型参数:
If your callback needs to have something passed to it, you can use a type parameter on Action
:
public static void DoWork(Action<string> processAction)
{
// do work
if (processAction != null)
processAction("this is the string");
}
public static void Main()
{
// using anonymous delegate
DoWork(delegate(string str) { Console.WriteLine(str); });
// using Lambda
DoWork((str) => Console.WriteLine(str));
}
如果需要多个参数,可以在Action
中添加更多类型参数.如果您需要返回类型,如上所述使用 Func
并使返回类型成为 last 类型参数(Func
是一个函数接受一个字符串并返回一个整数.)
If it needs multiple arguments, you can add more type parameters to Action
. If you need a return type, as mentioned use Func
and make the return type the last type parameter (Func<string, int>
is a function accepting a string and returning an int.)
有关代表的更多信息 这里.
More about delegates here.
public interface IObjectWithX
{
void X();
}
public class MyObjectWithX : IObjectWithX
{
public void X()
{
// do something
}
}
public class ActionClass
{
public static void DoWork(IObjectWithX handlerObject)
{
// do work
handlerObject.X();
}
}
public static void Main()
{
var obj = new MyObjectWithX()
ActionClass.DoWork(obj);
}
这篇关于C#中的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!