显式接口实现不能是虚拟的 [英] Explicit interface implementation cannot be virtual

查看:153
本文介绍了显式接口实现不能是虚拟的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了记录,我已经看到了这个连接项目,但我不能真正理解支持这个问题会是什么。

For the record, I've already seen this connect item but I can't really understand what would be the problem in supporting this.

说我有以下代码:

public interface IInterface
{
    void Method();
}

public class Base : IInterface
{
    virtual void IInterface.Method()
    {
        throw new NotImplementedException();
    }
}

虚拟标识符有什么问题?使用虚拟修饰符可以覆盖,表明基类中有不同的实现。我现在可以通过删除虚方法并创建如下的派生类来使其工作:

what is the problem with the virtual identifier? Having a virtual modifier would make it possible to override indicating there's a different implementation in the base class. I can make it work now by removing the virtual method and creating the derived class like this:

public class Derived : IInterface
{
    void IInterface.Method()
    {
        throw new NotImplementedException();
    }
}

然而这种方式我根本没有迹象表明我压倒了什么。

however this way I've really no indication at all that I'm overriding something.

更新:

根据C#(部分:20.4.1显式接口成员实现)规范,有2个原因。

Update:
According to the C# (part: 20.4.1 Explicit interface member implementations) spec there are 2 reasons.


  1. 隐藏某些方法(我正在使用它)。

  2. 拥有2个具有相同签名但返回类型不同的函数
    (例如ICELable的用途)。

它没有说明为什么你不能将这些方法变为虚拟。

It doesn't say anything however about why you can't make these methods virtual.

Update2: < br>
鉴于答案,我想我应该在这里重新提出真正的问题。如果以上两个原因是首先使接口的显式实现成为可能的原因。如果将方法设为虚拟,为什么会出现问题?

Update2:
Given the answers I think I should rephrase the real question here. If The above 2 reasons are the reason why explicit implementation of interfaces was made possible in the first place. Why would it be a problem if you make a method virtual.

推荐答案


然而这种方式我根本没有迹象表明我压倒了什么

however this way I've really no indication at all that I'm overriding something

嗯,你可以这样做 - 你知道它显然是一个明确的接口实现。这表明它为在接口上指定的方法调用提供了多态行为...为什么基类是否实现了接口?当你阅读代码时它会给你带来什么不同?

Well, you do, sort of - you have the fact that it's clearly an explicit interface implementation. That shows it's providing polymorphic behaviour for that method call which is specified on an interface... why does it matter whether the base class also implemented the interface? What difference will it make to you when you read the code?

对我来说,陈述的主要好处是覆盖是为了确保我真正得到了正确的签名 - 它与我试图覆盖的东西相匹配。你已经通过显式接口实现获得了这个好处,就好像你提供了一个不存在的方法或错误的参数等,编译器已经会抱怨了。

To me, the main benefit of stating override is to make sure I've really got the right signature - that it matches the thing I'm trying to override. You've already got that benefit with explicit interface implementation, as if you give a non-existent method or the wrong parameters etc, the compiler will already complain.

我可以排序看到你的观点,但我从未发现它是一个实际问题。

I can sort of see your point, but I've never found it to be an actual problem.

这篇关于显式接口实现不能是虚拟的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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