开发者

C# How to do this anonymous method injection

How do I use something like this in C#.

 Console.WriteLine("yaya instant");
 Server.registerEvent(new Event(5000) {
    public void doWork() {
        this.stop();
        Console.WriteLine("yaya 5 seconds later");
    }
  });
开发者_C百科

Event class and the doWork() method is declared inside Event class.

Pretty much what is going on is doWork() is abstract method which should get created by the code above.

Whats the proper syntax to do this in C#? is it even possible to do anonymous methods like this?. (The above code is not valid syntax, if someone doesn't understand this question.)

Thank you I appreciate the help.


No you can't do this. You need to create a sub class of Event that accepts an action.

public class MyEvent: Event
{
    private Action _action;        

    public MyEvent(int milliseconds, Action action)
        : base(milliseconds)
    {
        _action= action;
    }

    public override void doWork()
    {
        action()
    }
}

Then you can do this:

Server.registerEvent(new MyEvent(5000, () => 
    {
        this.stop();
        Console.WriteLine("yaya 5 seconds later");
    }));

You just need to declare MyEvent once (call it something better), and then you can create instances of it with different actions when you need them.


You can't have anonymous classes in C#. Is that what you are asking? But in C# you normally wouldn't implement a class for handling an event anyway.


The closest thing I can think of is this:

using System;
using System.Threading;

namespace SO6304593
{    
    class Program
    {
        static void Main(string[] args)
        {
             Console.WriteLine("yaya instant");

            Thread t1 = new Thread(delegate(object x) { Thread.Sleep((int)x); Console.WriteLine("Hello 1");});
            Thread t2 = new Thread(x => {Thread.Sleep((int)x); Console.WriteLine("Hello 2");});

            t1.Start(5000);
            t2.Start(3000);
            t1.Join();
            t2.Join();
        }
    }
}

Is this what you are after? The above are two examples of using anonymous methods in C#: the delegated syntax and the lambda syntax.


Give your event class a property of type Action:

public class Event
{
    public Action doWork { get; set; }
}

Then use as follows:

Console.WriteLine("yaya instant");
Server.registerEvent(new Event(5000) {
    doWork = delegate {
        this.stop();
        Console.WriteLine("yaya 5 seconds later");
    }
});


To achieve the method injection add an Action arg in the constructor to Event then you could do it like this;

Console.WriteLine("yaya instant");
Server.registerEvent(
    new Event(5000, () {
        stop();
        Console.WriteLine("yaya 5 seconds later");
        )
    );

Event::Event(int time, Action action){...}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜