我对接口的实现感到困惑。
根据MSDN ICollection<T>
有财产IsReadOnly
-和-
根据MSDN Collection<T>
实现ICollection<T>
-所以-
我以为Collection<T>
会有财产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);
上面的代码有效。
-问题-
我认为实现接口的类必须实现每个属性,那么为什么没有testCollection
该IsReadOnly
属性,除非您将其转换为ICollection<string>
?