我对接口(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)的类必须实现每个属性,所以为什么不 testCollection
有 IsReadOnly
属性(property),除非您将其转换为 ICollection<string>
?
最佳答案
它可能正在显式实现属性。
C# 使您能够将方法定义为“显式实现的接口(interface)方法/属性”,只有在您具有确切接口(interface)的引用时它们才可见。这使您能够提供一个“更干净”的 API,没有那么多噪音。
关于c# - 实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18020147/