c# - 实现接口(interface)

标签 c# .net inheritance interface

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

根据 MSDN ICollection<T>拥有属性(property) IsReadOnly

-和-

根据 MSDN Collection<T>工具 ICollection<T>

-所以-

我认为 Collection<T>将拥有属性(property) IsReadOnly .

-然而-

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

以上代码给出编译错误:

'System.Collections.ObjectModel.Collection<string>' does not contain a definition for 'IsReadOnly' and no extension method 'IsReadOnly' accepting a first argument of type

'System.Collections.ObjectModel.Collection<string>' 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);

上面的代码有效。

-问题-

我认为实现接口(interface)的类必须实现每个属性,所以为什么不 testCollectionIsReadOnly属性(property),除非您将其转换为 ICollection<string>

最佳答案

它可能正在显式实现属性。

C# 使您能够将方法定义为“显式实现的接口(interface)方法/属性”,只有在您具有确切接口(interface)的引用时它们才可见。这使您能够提供一个“更干净”的 API,没有那么多噪音。

关于c# - 实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18020147/

相关文章:

c# - 无法将参数传递给存储过程: parameters not supplied

.net - 在 Visual Studio 快速观察窗口中查看流的内容

c++ - 为什么我的基类构造函数之一被删除? (C++11)

c# - 在通用词典中找不到键

C# Facebook SDK 将 accesstoken 延长至 60 天

ASP.NET Identity 与自定义实现,使用哪一个?

c++基类包含派生类的实例

c# - C# 不支持多重继承,那么我怎样才能让它工作呢?

c# - WPF面板旋转?

c# - SpecFlow 可重用步骤定义