【问题标题】:Class Keyword - Explicitly Indicating Inherited Interfaces?类关键字 - 显式指示继承的接口?
【发布时间】:2016-11-07 23:09:29
【问题描述】:

SqlDataReader's 类语句包括 IDataReader、IDataRecord 和 IDisposable,尽管这些都由其基类 DbDataReader 实现:

public class SqlDataReader : DbDataReader, 
  IDataReader, IDisposable, IDataRecord {...}

public abstract class DbDataReader : MarshalByRefObject, 
  IDataReader, IDisposable, IDataRecord, IEnumerable {...}

在这种情况下,指示派生类实现其基类已经指示它实现的接口是否有一些技术优势? (我想不出一个。想知道这是遗留的遗物、错字还是出于文档目的。)

【问题讨论】:

  • 你在哪里看到的?在referencesource.microsoft.com 网站上看不到这个。
  • @Dmitry,IDataReader 两者都定义了,但答案是否定的,没有理由添加多余的接口声明。
  • @KirkWoll 显式接口实现怎么样? SqlDataReader 类中有一个:IDataReader IDataRecord.GetData(int i)
  • @Dmitry,啊,很好。所以毕竟不是多余的。
  • 谢谢@Dmitry!我错过了。这是有道理的。

标签: c# class interface sqldatareader


【解决方案1】:

这样做可以在派生类中添加或覆盖显式接口实现。例如,

interface IFoo
{
    string P {get;}
}

class Base: IFoo
{
    string IFoo.P 
    {
        get { return "Base"; }
    }
}

class Derived: Base, IFoo
{
    string IFoo.P 
    {
        get { return "Derived"; }
    }
}

如果Derived不直接实现IFoo,则无法定义IFoo.P的显式实现,因此无法覆盖基类中的实现。

【讨论】:

    【解决方案2】:

    如果您想显式实现某些接口,这很有意义。
    例如:

    interface ISome
    {
        void Method();
    }
    
    class A : ISome
    {
        public void Method()
        {
        }
    }
    
    class B : A, ISome // Try to remove ISome...
    {
        void ISome.Method()
        {
        }
    }
    

    如果注释掉B声明中的ISome,编译会失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 2010-12-23
      • 2011-06-21
      • 2022-01-04
      • 2021-05-08
      • 2017-05-07
      相关资源
      最近更新 更多