是否可以命名索引器属性?
假设我在类中有一个数组或任何其他集合,以及一个返回它的属性,如下所示:
public class Foo { public IList Bars{get;set;} }
现在,我可以这样写:
public Bar Bar[int index] { get { //usual null and length check on Bars omitted for calarity return Bars[index]; } }
根据您真正寻找的内容,可能已经为您完成了。 如果您正尝试在Bars集合上使用索引器,那么它已经为您完成了::
Foo myFoo = new Foo(); Bar myBar = myFood.Bars[1];
或者,如果您尝试获得以下function:
Foo myFoo = new Foo(); Bar myBar = myFoo[1];
然后:
public Bar this[int index] { get { return Bars[index]; } }
不 – 你不能在C#中编写命名索引器。 从C#4开始,您可以为COM对象使用它们,但是您无法编写它们。
然而,正如你所注意到的那样, foo.Bars[index]
无论如何都会做你想要的……这个答案主要是为了未来的读者。
详细说明:公开具有索引器的某种类型的Bars
属性可以实现您想要的,但您应该考虑如何公开它:
- 您是否希望呼叫者能够使用不同的集合替换集合? (如果没有,请将其设为只读属性。)
- 您是否希望呼叫者能够修改集合? 如果是这样,怎么样? 只是更换物品,或添加/删除它们? 你需要控制吗? 这些问题的答案将决定您要公开的类型 – 可能是只读集合,或具有额外validation的自定义集合。
但是,您可以滚动自己的“命名索引器”。 看到
- 为什么C#没有实现索引属性?
- 轻松创建支持C#索引的属性
您可以使用显式实现的接口,如下所示: C#中的命名索引属性? (见该回复中显示的第二种方式)
public class NamedIndexProp { private MainClass _Owner; public NamedIndexProp(MainClass Owner) { _Owner = Owner; public DataType this[IndexType ndx] { get { return _Owner.Getter(ndx); } set { _Owner.Setter(ndx, value); } } } public MainClass { private NamedIndexProp _PropName; public MainClass() { _PropName = new NamedIndexProp(this); } public NamedIndexProp PropName { get { return _PropName; } } internal DataType getter(IndexType ndx) { return ... } internal void Setter(IndexType ndx, DataType value) { ... = value; } }