【问题标题】:Implementing an interface实现接口
【发布时间】:2013-08-03 21:59:18
【问题描述】:

我对接口的实现感到困惑。

根据MSDNICollection<T>有属性IsReadOnly

-和-

根据MSDNCollection<T>实现ICollection<T>

-所以-

我认为Collection<T> 将拥有IsReadOnly 的属性。

-然而-

Collection<string> testCollection = new Collection<string>();
Console.WriteLine(testCollection.IsReadOnly);

以上代码给出编译错误:

'System.Collections.ObjectModel.Collection&lt;string&gt;' does not contain a definition for 'IsReadOnly' and no extension method 'IsReadOnly' accepting a first argument of type

'System.Collections.ObjectModel.Collection&lt;string&gt;' could be found (are you missing a using directive or an assembly reference?)

-同时-

Collection<string> testInterface = new Collection<string>();
Console.WriteLine(((ICollection<string>)testInterface).IsReadOnly);

上面的代码有效。

-问题-

我认为实现接口的类必须实现每个属性,那么为什么 testCollection 没有 IsReadOnly 属性,除非您将其转换为 ICollection&lt;string&gt;

【问题讨论】:

标签: c# .net inheritance interface


【解决方案1】:

它可能正在显式地实现该属性

C# 使您能够将方法定义为“显式实现的接口方法/属性”,这些方法仅在您具有确切接口的引用时才可见。这使您能够提供“更干净”的 API,而不会产生太多噪音。

【讨论】:

    【解决方案2】:

    接口可以通过多种方式实现。显式和隐式。

    显式实现:当成员显式实现时,不能通过类实例访问,只能通过接口实例访问

    隐式实现:可以像访问类一样访问接口方法和属性。

    IsReadonly 属性是显式实现的,因此不能通过类直接访问。看看here

    例子:

    public interface ITest
    {
        void SomeMethod();
        void SomeMethod2();
    }
    
    public ITest : ITest
    {
    
        void ITest.SomeMethod() {} //explicit implentation
        public void SomeMethod2(){} //implicity implementation
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-20
    • 2013-09-25
    • 2011-08-28
    • 2014-08-21
    • 2017-07-02
    • 2015-11-08
    • 2012-08-26
    相关资源
    最近更新 更多