开发者

Problem Overloading Indexer in C#

i got a problem while overloading indexer property.

public class ClassName 
{
    private int[] a;
    private int[] b;
    private string[] c;
    private string[] d;

    public int this[int pos]
    {
        get{ return a[pos];}
  开发者_C百科      set{a[pos] = value;}
    }
    public int this[int pos]
    {
        get{ return b[pos];}
        set{b[pos] = value;}
    }
    public int this[int pos]
    {
        get{ return c[pos];}
        set{c[pos] = value;}
    }
    public int this[int pos]
    {
        get{ return d[pos];}
        set{d[pos] = value;}
    }
}

I am getting Error 1 'Class1 variables' already defines a member called 'this' with the same parameter types

Please suggest me how to implement this?


You defined this[] with the same signature (taking an int, returning an int) multiple times.

How does the compiler know which one to take?

Better make your arrays Properties (this time indexed properties would really come in handy!)

And make your set method for your properties private, otherwise they can overwrite the array instead of just changing values.

So to help the TS a little bit more:

public class Test
{
    private string[] _a;
    private int[] _b;

    public string[] A
    {
        get { return this._a; }
        private set { this._a = value; }
    }

    public int[] B
    {
        get { return this._b; }
        private set { this._b = value; }
    }

    public Test()
    {
        // todo add ctor logic here
    }
}

// now you can do:

Test t = new Test();

t.A[1] = "blah"; // assuming that index of the array is defined.

Good luck


Imagine this indexer being called by another class:

ClassName myClass = new ClassName();
myClass[0]; // Which one???


The error means what it says. You have four properties with exactly the same signature.

What are you trying to do? Show what you expect the code using ClassName to look like.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜