C# Multiple Indexers

后端 未结 7 1076
深忆病人
深忆病人 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条回答
  •  无人及你
    2020-12-30 05:47

    If you're trying to do something like this:

    var myClass = new MyClass();
    
    Console.WriteLine(myClass.Foos[0]);
    Console.WriteLine(myClass.Bars[0]);
    

    then you need to define the indexers on the Foo and Bar classes themselves - i.e. put all the Foo objects inside Foos, and make Foos a type instance that supports indexing directly.

    To demonstrate using arrays for the member properties (since they already support indexers):

    public class C {
        private string[] foos = new string[] { "foo1", "foo2", "foo3" };
        private string[] bars = new string[] { "bar1", "bar2", "bar3" };
        public string[] Foos { get { return foos; } }
        public string[] Bars { get { return bars; } }
    }
    

    would allow you to say:

     C myThing = new C();
     Console.WriteLine(myThing.Foos[1]);
     Console.WriteLine(myThing.Bars[2]);
    

提交回复
热议问题