我對接口的實現感到困惑。實現接口
根據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-
我想實現接口的類必須實現每個屬性,那麼爲什麼不testCollection
有IsReadOnly
財產,除非你將它轉換爲ICollection<string>
?
看到http://stackoverflow.com/questions/143405/c-sharp-interfaces-implicit-implementation-versus-explicit-implementation?rq=1一個更好的交代 – Mgetz