C# Multiple Indexers

后端 未结 7 1063
深忆病人
深忆病人 2020-12-30 05:10

Is it possible to have something like the following:

class C
{
    public Foo Foos[int i]
    {
        ...
    }

    public Bar Bars[int i]
    {
        .         


        
7条回答
  •  旧时难觅i
    2020-12-30 05:47

    Not in C#, no.

    However, you can always return collections from properties, as follows:

    public IList Foos
    {
        get { return ...; }
    }
    
    public IList Bars
    {
        get { return ...; }
    }
    

    IList has an indexer, so you can write the following:

    C whatever = new C();
    Foo myFoo = whatever.Foos[13];
    

    On the lines "return ...;" you can return whatever implements IList, but you might what to return a read-only wrapper around your collection, see AsReadOnly() method.

提交回复
热议问题