实现接口

jem*_*n80 4 .net c# inheritance interface

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

根据MSDN ICollection<T>的财产IsReadOnly

-和-

根据MSDN Collection<T>实现ICollection<T>

-所以-

我以为那Collection<T>会有财产IsReadOnly.

-然而-

Collection<string> testCollection = new Collection<string>();
Console.WriteLine(testCollection.IsReadOnly);
Run Code Online (Sandbox Code Playgroud)

上面的代码给出了编译错误:

'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);
Run Code Online (Sandbox Code Playgroud)

上面的代码有效.

-题-

我想实现接口必须实现每个属性类,所以为什么不testCollectionIsReadOnly,除非你将它转换为财产ICollection<string>

D.R*_*.R. 10

它可能是明确地实现了属性.

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