How to hide some members of an interface

2019-01-19 16:41发布

I would like to create a custom collection that implements ICollection.

But I would like not to expose some memebers of ICollection like Clear method.

How to achieve this?

7条回答
一纸荒年 Trace。
2楼-- · 2019-01-19 17:25

If you just want to hide those members from your own collection's interface, you can define them explicitly.

void ICollection.Clear() {
    // ...
}

Explicitly defined members are only available if the instance is used through that interface.

YourCollection col1 = new YourCollection();
col1.Clear(); // this is not allowed if clear is defined explicitly

ICollection col2 = new YourCollection();
col2.Clear(); // this will work because col2 is ICollection
查看更多
登录 后发表回答