6

假设我在类中有一个数组或任何其他集合,以及一个返回它的属性,如下所示:

public class Foo
{
    public IList<Bar> Bars{get;set;}
}

现在,我可以写这样的东西:

public Bar Bar[int index]
{
    get
    {
        //usual null and length check on Bars omitted for calarity
        return Bars[index];
    }
}
4

5 回答 5

15

不 - 您不能在 C# 中编写命名索引器。从 C# 4 开始,您可以将它们用于 COM 对象,但不能编写它们。

但是,正如您所注意到的,无论如何foo.Bars[index]都会做您想做的事情……这个答案主要是为了未来的读者。

详细说明:公开Bars具有索引器的某种类型的属性可以实现您想要的,但您应该考虑如何公开它:

  • 您是否希望调用者能够用不同的集合替换集合?(如果没有,请将其设为只读属性。)
  • 您希望调用者能够修改集合吗?如果是这样,怎么做?只是更换项目,或添加/删除它们?您需要对此进行任何控制吗?这些问题的答案将决定您要公开的类型——可能是只读集合,或者具有额外验证的自定义集合。
于 2010-07-20T19:22:07.820 回答
1

但是,您可以滚动自己的“命名索引器”。看

于 2010-07-27T14:38:09.320 回答
1

您可以使用显式实现的接口,如下所示: C# 中的命名索引属性?(请参阅该回复中显示的第二种方式)

于 2016-05-30T03:10:30.377 回答
1
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;
    }
}
于 2017-10-18T00:15:20.547 回答
0

根据您真正在寻找什么,它可能已经为您完成了。如果您尝试在 Bars 集合上使用索引器,它已经为您完成了::

Foo myFoo = new Foo();
Bar myBar = myFoo.Bars[1];

或者,如果您尝试获得以下功能:

Foo myFoo = new Foo();
Bar myBar = myFoo[1];

然后:

public Bar this[int index]
{
    get { return Bars[index]; }
}
于 2010-07-20T19:18:10.483 回答