Alternatives inline interface implementation in C#

2019-04-11 12:26发布

问题:

I'd like to use inline interface implementation in C# but reading some posts like this or this I found out that it's not like Java do it.

Supposing this interface:

public interface MyListener {
    void onHandleOne();
    void onHandleTwo();
    }

and I pass this interface as a parameter:

   myMethod(MyListener listener){
    //some logic
   }

and when I call it I'd like to do inline imlementation like in java:

myMethod(new MyListener () {
                    @Override
                    public void onHandleOne() {
                        //do work
                    }

                    @Override
                    public void onHandleTwo() {
                        //do work
                    }
                });

As an alternative I made a class that implements yhis interface and use this class to call my method:

public class MyImplementor : MyListener  {
    public void onHandleOne() {
        //do work
        }

    public void onHandleTwo() {
        //do work
        }
    }

and call my method: myMethod(new MyImplementor()) but this solutions needs a new class every time I'll call this method (for different behavior) maybe is there a way using lambda or somehow to do it like:

myMethod(new MyImplementor() =>{//handle my methods})

回答1:

but this solutions needs a new class every time I'll call this method (for different behavior) maybe is there a way using lambda or somehow to do it like

Yes, give it a delegate parameter and pass it a lambda.

public class MyImplementor : MyListener  
{
    private readonly Action handle1;
    private readonly Action handle2;
    public MyImplementor(Action handle1, Action handle2)
    {
        this.handle1 = handle1;
        this.handle2 = handle2;
    }

    public void onHandleOne() 
    {
       handle1();
    }

    public void onHandleTwo()
    {
       handle2();
    }
}

Then you can use it as

myMethod(new MyImplementor(()=>{//handle method1}, ()=>{//Handle method2});