2017-04-13 34 views
-1

我有問題(我認爲)與派生類。當我在Form 1的列表中添加一些點時,我可以看到count和迭代listA,並且它看起來沒問題。我有下面的代碼:C#派生類不傳遞值?

/* Add points to lists */ 
class A { 
    private Point _singlePoint; 
    protected List<Point> _listA = new List<Point>(); 
    protected List<Point> _listB = new List<Point>(); 

    //properties 
    public List<Point> listA { 
     get { return _listA; } 
     set { _listA = value; } 
    } 

    public Point singlePoint { 
     get { return _singlePoint; } 
     set { _singlePoint = value; } 
    } 

    public virtual void addToListA(Point a) { } 
} 

class B : A { 
    public override void addToListA(Point a) { 
     _listA.Add(a); 
    } 
} 

public partial class Form1 : Form { 

    A _myPoints = new B(); 
    private void drawPoint() 
    { 
     for (int i = 0; i < int.Parse(txtBoxPointsCount.Text); i++) 
     { 
      _myPoints.singlePoint = new Point(rnd.Next(100, 300), rnd.Next(100, 300)); 
      _myPoints.addToListA(_myPoints.singlePoint); 
     } 

     foreach(Point p in _myPoints.listA) 
     { 
      graph.FillEllipse(new SolidBrush(cPoint), p.X, p.Y, 6, 6); 
     } 
    } 
} 

在其他類我想要做點一些數學,但我得到了ArgumentOutOfRangeException

class D { 
    A _myPoints = new B(); 
    public void calulations(int iterations) { 
     randomPoint = rnd.Next(0, _myPoints.listA.Count); 
     System.Windows.Forms.MessageBox.Show(_myPoints.listA.Count.ToString()); 

     try { 
      for (int i = 0; i < _iterations; i++) { 
       //here some math 
      } 
     } 
     catch(ArgumentOutOfRangeException e) { 
      // here I got errors about no items in my list 
     } 
    } } 

在d類,在MSGBOX我數= 0。也許是我寫的錯誤的方式?在calculations()之前調用方法drawPoint()

你能幫忙嗎?謝謝

+1

我覺得[實例成員]有一些基本的困惑(https://msdn.microsoft.com/en-us/library/aa645629(v = vs.71).aspx)。 –

回答

1

那是因爲您在操作兩個完全不同的對象,

你已經創建這裏的對象

public partial class Form1 : Form 
{ 
    A _myPoints = new B(); 

和提前:)然後在此類d創造了另一個

class D 
{ 
    A _myPoints = new B(); 

因此,您要爲第一個對象添加點並嘗試訪問其他對象。