【发布时间】:2013-08-03 21:59:18
【问题描述】:
我对接口的实现感到困惑。
根据MSDNICollection<T>有属性IsReadOnly
-和-
根据MSDNCollection<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>?
【问题讨论】:
-
查看stackoverflow.com/questions/143405/…以获得更好的解释
标签: c# .net inheritance interface