2010-05-26 81 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???