简体   繁体   English

C#+替代委托

[英]C# + Overrride Delegate

I have some code that is using a third-party library that I can't bypass. 我有一些代码正在使用无法绕过的第三方库。 This library provides some auxiliary features that I need. 该库提供了我需要的一些辅助功能。 At this time, my code is setup like this: 目前,我的代码是这样设置的:

static Engine engine = new Engine();

static void Main(string[] args)
{
   engine.Execute(MyCode); 
}

private static void MyCode()
{
  // my code goes here
}

Here's my challenge: I have to instantiate some code before MyCode can use it because that instantiation must hit a database and takes longer than the threshold allowed by Engine . 这是我的挑战:在MyCode可以使用它之前,我必须实例化一些代码,因为实例化必须命中数据库,并且花费的时间比Engine允许的阈值长。 I can't use a static variable because multiple instances will be necessary. 我不能使用静态变量,因为将需要多个实例。 Which basically means, I want something like this: 这基本上意味着,我想要这样的东西:

static Engine engine = new Engine();

static void Main(string[] args)
{
   MyClass c = new MyClass();
   c.Initialize();  // This is the db call

   engine.Execute(MyCode); // This line is the problem
}

private static void MyCode(MyClass c)
{
  // my code goes here
  c.DoStuff();
}

My problem is, I basically need to create an overloaded method that takes a parameter. 我的问题是,我基本上需要创建一个带参数的重载方法。 However, the Execute method in the third-party library doesn't let me do that. 但是,第三方库中的Execute方法不允许我这样做。 Is there some C# syntactial way I can do this that I'm missing? 有没有我可以做的一些C#语法方式来做到这一点?

您正在寻找lambda表达式:

engine.Execute(() => MyCode(c));

I'm assuming that Engine.Execute takes an instance of Action . 我假设Engine.Execute带有Action的实例。

You could make the MyCode function an instance member function on MyClass , then pass MyClass.MyCode to Engine.Execute as an Action . 您可以使MyCode函数成为MyClass上的实例成员函数,然后将MyClass.MyCode作为Action传递给Engine.Execute

public class Engine
{
    public void Execute(Action action)
    {
        action.Invoke();
    }
}

public class MyClass
{
    public void Initialize()
    {
        System.Threading.Thread.Sleep(500); //Simulate some work.
    }

    public void Run()
    {
        // I've renamed it from MyCode to Run, but this method is essentially your
        // my code method.
        Console.WriteLine($"I'm being run from the engine! My Id is {_id}.");
    }

    private readonly Guid _id = Guid.NewGuid();
}

public static class Program
{
   static void Main(string[] args)
   {
      var engine = new Engine();
      var c = new MyClass();
      c.Initialize();
      engine.Execute(c.Run);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM