可转位接口 [英] Indexable interface

查看:172
本文介绍了可转位接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么C#接口应该被使用,如果我只希望能够索引到一类型的实例?我不需要(或希望)来添加/删除/编辑元素的能力。枚举是好的。这是否需要自定义 IIndexable 键入<?/ p>

在这种情况下,的IList 是矫枉过正,因为它迫使执行委员,我不希望有。


解决方案

IList的<> (假设你要保持通用)是包括索引的唯一接口。



不过,你可以明确地执行,并抛出引发NotSupportedException 为所有那些你不想来支持运营,或只是实施的IEnumerable<方式> 和对类剩下的只有,而不是在一个接口


What C# interface should be used if I only want to be able to index into instances of a type? I don't need (or want) the ability to add/remove/edit elements. Enumeration is okay. Does this require a custom IIndexable type?

In this case IList is overkill because it forces implementation of members I don't want to have.

解决方案

IList<> (assuming you want to stay generic) is the only interface to include an indexer.

However, you can just explicitly implement and throw NotSupportedException for all those operations you don't want to support, or just implement IEnumerable<> and have the rest on the class only, not in an interface.

这篇关于可转位接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆