如何才能访问类中数组的元素

时间:2013-07-28 23:28:18

标签: c# winforms

我有一个我不知道如何解决的问题。我上课了。这个类有两个数组。我想通过属性访问。我该怎么做?我试图使用索引器,但如果我只有一个数组,那就有可能。这就是我想要做的事情:

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;

3 个答案:

答案 0 :(得分:1)

Tuples的一个例子。

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

答案 1 :(得分: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];

答案 2 :(得分:0)

如果没有更改数据结构或移动到方法,最接近的就是创建一个返回每个数组的属性,就像在第一个代码块中一样,除了没有[i]。

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