C# equivalent of creating anonymous class that implements an interface

后端 未结 2 1103
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 17:33

I\'ve recently started using C#, and I wanted to find an equivalent method to this. I do not know what this is called, so I will simply show you by code.

With Java,

2条回答
  •  爱一瞬间的悲伤
    2020-12-11 17:55

    EDIT: It looks like your question is about anonymous interface implementations instead of events. You can use the built-in Action delegate type instead of your Event interface.

    You can then Action instances using lambda expressions. Your code would look like:

    public class TestEvent
    {
        List eventList = new List();
    
        public void addEvent(Action event){
            eventList.add(event);
        }
    
        public void simulateEvent(){
            addEvent(() => {
            });
        }
    
        public void processEvents(){
            for(Action event : eventList)
                event();
        }
    }
    

    You can use the delegate syntax instead of using () => { .. .} i.e. delegate() { ... } in simulateEvent.

    C# doesn't support anonymous interface implementations, so if your interface has multiple methods then you'll have to define a concrete class somewhere. Depending on the usage you could just have this class contain delegate properties which you can supply on creation e.g.

    public class Delegates
    {
        public Action Event { get; set; }
        public Func GetValue { get; set; }
    }
    

    You can then create it like:

    var anon = new Delegates
    {
        Event = () => { ... },
        GetValue = () => "Value"
    }
    

提交回复
热议问题