开发者社区> 问答> 正文

为什么java可以实例化接口

private void doWebLogin(String verifyCode, final ProcActionFuture future) {
    LoginModule login =  getContext().getModule(QQModule.Type.LOGIN);
    QQAccount account = getContext().getAccount();
    login.webLogin(account.getUsername(), account.getPassword(),
            account.getUin(), verifyCode, new QQActionListener() {    // 此处的QQActionListener是个接口,在下面
                public void onActionEvent(QQActionEvent event) {
                    if (event.getType() == QQActionEvent.Type.EVT_OK) {
                        doCheckLoginSig( (String) event.getTarget(),future);
                    } else if (event.getType() == QQActionEvent.Type.EVT_ERROR) {
                        QQException ex = (QQException) (event.getTarget());
                        if(ex.getError()==QQErrorCode.WRONG_CAPTCHA){
                            doGetVerify(ex.getMessage(), future);
                        }else{
                            future.notifyActionEvent(
                                    QQActionEvent.Type.EVT_ERROR,
                                    (QQException) event.getTarget());
                        }
                    }
                }
            });
}
public interface QQActionListener {
    public void onActionEvent(QQActionEvent event); 
}

那么这种语法在C#里怎么【更好的】移植呢?
我现在的做法是重写一个类,继承QQActionListener,然后在实例化。
但是这种写法在这个项目中比较多,所以要为了一个方法就要重新写一个类,实在是太难看了。
请问有什么方法能更好的该写如上面的那样的java语法到C#吗

展开
收起
蛮大人123 2016-02-27 19:28:56 2928 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    可以使用委托来模拟实现,单方法的接口直接用委托(Lambda表达式)解决,当然这个需要上层接口允许使用委托才行。多方法的接口需要实现一个辅助类

    public interface IQQActionListener {
        void OnActionEvent(QQActionEvent event);
    }
    public class Something {
        private void doWebLogin() {
            login.webLogin(name, password, new DelegateQQActionListener {
                ActionEvent = (event) => {
                    // event is a QQActionEvent reference
                    if (event.getType() == QQActionEvent.Type.EVT_OK) {
    
                    } else {
    
                    }
                }
            })
        }
        private class DelegateQQActionListener: IQQActionListener {
            public Action < QQActionEvent > ActionEvent {
                get;
                set;
            }
    
            public OnActionEvent(QQActionEvent event) {
                if (ActionEvent != null) {
                    ActionEvent(event)
                }
            }
        }
    }
    2019-07-17 18:49:17
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载