2013-07-28 45 views
1

我有一个问题,我不知道如何解决。我有一堂课。这个类有两个数组。我想通过属性访问。我该怎么做?我试图使用索引器,但如果我只有一个数组,它是可能的。这里是我想做的事:我怎样才能访问类中的数组元素

public class pointCollection 
{ 
    string[] myX; 
    double[] myY; 
    int maxArray; 
    int i; 
    public pointCollection(int maxArray) 
    { 
     this.maxArray = maxArray; 
     this.myX = new string[maxArray]; 
     this.myY = new double[maxArray];   
    } 
    public string X //It is just simple variable 
    { 
     set { this.myX[i] = value; } 
     get { return this.myX[i]; }    
    } 
    public double Y //it's too 
    { 
     set { this.myY[i] = value; } 
     get { return this.myY[i]; }    
    } 
} 

有了这个代码,我的X和Y是只有简单的变量,而不是数组。 如果我使用索引,我得到的只能访问一个数组:

public string this[int i] 
    { 
     set { this.myX[i] = value; } 
     get { return this.myX[i]; }    
    } 

但我怎么能访问第二阵列? 或者我不能在这种情况下使用财产?我只需要使用:

public string[] myX; 
    public double[] myY; 
+2

您可以使用组<字符串,双>的数组? – user467384

+0

是否有可能使用不同类型的数据的数组? – mit

+0

为什么要分别存储x和y?像Point这样的结构可能会给你一个数组并且索引器可以工作,不是吗? –

回答

0

如果我说得对,您需要一些种类或读/写包装数组作为属性暴露。

public class ReadWriteOnlyArray<T>{ 

    private T[] _array; 

    public ReadWriteOnlyArray(T[] array){ 
     this._array = array; 
    } 

    public T this[int i]{ 
     get { return _array[i]; } 
     set { _array[i] = value; } 
    } 
} 

public class pointCollection 
{ 
    string[] myX; 
    double[] myY; 
    int maxArray; 

    public ReadWriteOnlyArray<string> X {get; private set;} 
    public ReadWriteOnlyArray<double> Y {get; private set;} 

    public pointCollection(int maxArray) 
    { 
     this.maxArray = maxArray; 
     this.myX = new string[maxArray]; 
     this.myY = new double[maxArray];   
     X = new ReadWriteOnlyArray<string>(myX); 
     Y = new ReadWriteOnlyArray<double>(myY); 
    } 
} 

和使用

var c = new pointCollection(100); 
c.X[10] = "hello world"; 
c.Y[20] = c.Y[30] + c.Y[40]; 
+0

写下一个简单的例子。为什么不直接将数组属性设置为受保护集并使用它呢?你的包装类不会添加或删除任何东西。 – Xcelled194

+0

谢谢!一切正常! – mit

+0

@ Xcelled194除了索引器之外,数组实例还有很多方法,例如Resize()。诀窍是只在课堂外留下索引器。 – dmay

0

你会来没有更改你的数据结构或移动的方法最接近的是使返回每个数组的属性,就像你在你的第一个代码做块,除了没有[i]。

然后,你做了var x = instanceOfPointCollection.MyX[someI];例如。

1

元组的例子。

public class pointCollection 
{ 
    Tuple<String,Double>[] myPoints; 
    int maxArray; 
    int i; 
    public pointCollection(int maxArray) 
    { 
     this.maxArray = maxArray; 
     this.myPoints = new Tuple<String,Double>[maxArray]; 
    } 
    public Tuple<String,Double> this[int i] 
    { 
     set { this.myPoints[i] = value; } 
     get { return this.myPoints[i]; }    
    } 
} 

并访问你做点...

pointCollection pc = new pointCollection(10); 
// add some data 
String x = pc[4].Item1; // the first entry in a tuple is accessed via the Item1 property 
Double y = pc[4].Item2; // the second entry in a tuple is accessed via the Item2 property 
相关问题