实现接口 [英] Implementing an inteface
问题描述
我对接口的实现感到困惑。
ICollection< T>
有属性 IsReadOnly
根据 MSDN [ ^ ]
-And-
集合< T>
impliments ICollection< T>
根据 MSDN [ ^ ]
-So-
我以为 Collection< T>
会有property IsReadOnly
。
-However-
I'm confused about the implementation of interfaces.
ICollection<T>
has the property IsReadOnly
according to MSDN[^]
-And-
Collection<T>
impliments ICollection<T>
according to MSDN[^]
-So-
I thought that Collection<T>
would have the property IsReadOnly
.
-However-
Collection<string> testCollection = new Collection<string>();
Console.WriteLine(testCollection.IsReadOnly);
上面的代码给出了编译错误:
'System.Collections.ObjectModel .Collection< string>'不包含'IsReadOnly'的定义,并且没有扩展方法'IsReadOnly'接受类型为'System.Collections.ObjectModel.Collection< string>'的第一个参数'(你是否缺少using指令)或汇编参考?)
-While-
The above code gives the compiler error:
'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>
?
The above code works.
-Question-
I thought classes implementing interfaces had to implement every property, so why doesn't testCollection
have the IsReadOnly
property unless you cast it as ICollection<string>
?
推荐答案
IsReadOnly [ ^ ]属性明确实现。这意味着只有在将对象显式转换为ICollection< t>时才能调用此属性。
可以找到有关显式接口实现的更多信息其中 [ ^ ]
The IsReadOnly[^] property is implemented explicitely. That means you can only call this property when the object is explicitly cast to an ICollection<t>.
More info about explicit interface implementation can be found here[^]
这篇关于实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!