2013-08-02 158 views
4

我對接口的實現感到困惑。實現接口

根據MSDNICollection<T>擁有財產IsReadOnly

- 和 -

根據MSDNCollection<T>實現ICollection<T>

-SO-

我認爲Collection<T>將有屬性IsReadOnly

-However-

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?)

-While-

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

上面的代碼有效。

-Question-

我想實現接口的類必須實現每個屬性,那麼爲什麼不testCollectionIsReadOnly財產,除非你將它轉換爲ICollection<string>

+0

看到http://stackoverflow.com/questions/143405/c-sharp-interfaces-implicit-implementation-versus-explicit-implementation?rq=1一個更好的交代 – Mgetz

回答

3

接口可以通過幾種方式實現。顯式隱含。

顯式實現:如果成員被顯式實現,它不能通過類實例訪問,而只能通過接口的實例

隱實施:這些都可以訪問的接口方法和屬性就好像它們是類的一部分一樣。

IsReadonly屬性是明確實現的,因此它不能通過類直接訪問。看看here

例子:

public interface ITest 
{ 
    void SomeMethod(); 
    void SomeMethod2(); 
} 

public ITest : ITest 
{ 

    void ITest.SomeMethod() {} //explicit implentation 
    public void SomeMethod2(){} //implicity implementation 
} 
+0

謝謝爲信息。搜索後,我在http://msdn.microsoft.com/en-us/library/vstudio/ms173157找到了一個非常詳細的解釋。aspx – jemartin80

+0

@ jemartin80很高興幫助。我試圖找出Eric Lippert對此的非常詳細的描述。但我找不到它。 – Ehsan

10

它可能實施明確

C#使您可以將方法定義爲「顯式實現的接口方法/屬性」,只有在引用了確切的接口時纔可以看到。這使您可以提供「更清潔」的API,而不會產生太多噪音。