C#中的替代内联接口实现 [英] Alternatives inline interface implementation in C#

查看:132
本文介绍了C#中的替代内联接口实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C#中使用内联接口实现,但是阅读这样或者这样的帖子我发现它不像Java那样。

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.

假设这个interface:

Supposing this interface:

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

我将此接口作为参数传递:

and I pass this interface as a parameter:

   myMethod(MyListener listener){
    //some logic
   }

当我调用它时,我想像java一样进行内联插入:

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

作为替代方案,我创建了一个实现yhis接口的类,并使用此类调用我的方法: / p>

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
        }
    }

并调用我的方法: myMethod(new MyImplementor())
但这个解决方案每个都需要一个新类时间我会调用这个方法(对于不同的行为)也许有一种方法使用lambda或以某种方式这样做:

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()=> {//处理我的方法})

推荐答案


但是这个解决方案需要一个新的类,每次我都会调用这个方法
(针对不同的行为)也许有一种方法使用lambda或某种方式
来做它像

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

是,给它一个委托参数并传递一个lambda。

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

然后你可以用它作为

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

这篇关于C#中的替代内联接口实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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