2010-05-26 82 views
0

我在重载索引器属性时遇到了问题。
C中的问题重载索引器#

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

    public int this[int pos] 
    { 
     get{ return a[pos];} 
     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;} 
    } 
} 

我越来越Error 1 'Class1 variables' already defines a member called 'this' with the same parameter types

请建议我如何实现这一点?

+2

的问题是,你不重载索引器 - 你已经指定了4次相同的签名(另外,我认为其中两个应该返回'string')。我不认为C#支持命名索引器,所以你可能想重新考虑你的设计。 – 2010-05-26 07:21:32

回答

1

错误意味着它说了什么。您有四个签名完全相同的属性。

你想做什么?显示您期望代码使用 ClassName的样子。

3

您用相同的签名(取int,返回一个int)多次定义了这个[]。

编译器如何知道要采取哪一种?

更好的让你的阵列属性(此时索引的属性会真的派上用场了!)

,让你的一套方法,为你的私人性质,否则他们可以覆盖阵列,而不是仅仅改变的值。

所以,帮助TS多一点点:

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. 

好运

+1

我想这也许是OP所要做的事情? – 2010-05-26 07:23:51

2

想象一下这样的索引被另一个类被称为:

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