在C#回调 [英] Callbacks in C#

查看:130
本文介绍了在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.

我怎样才能做到这一点?

How can I do this?

有关引用我使用C#和.NET 3.5

For reference I'm using C# and .NET 3.5

推荐答案

供应委托并使用匿名委托或lambda表达式

Supply a delegate and use an anonymous delegate or Lambda Expression

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"));
}

或使用接口

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆