2011-09-07 61 views
1

enter image description here我有一个接口派生类问题使用接口

interface Dot 
{  
    // protected Random r = new Random(); 
    void createdot(Rectangle clientrectangle, Control.ControlCollection Controls); 
} 

,我使用这个接口作为一个基类为我的派生类的声明

public class BlueDot : Dot 
{ 
    public List<Label> bluedot = new List<Label>(); 
    Random r = new Random(); 

    public void createdot(Rectangle ClientRectangle, Control.ControlCollection Controls) 
    { 
     for (int i = 0; i < 5; i++) 
     { 
      var temp = new Label(); 

      temp.Location = new Point(r.Next(ClientRectangle.Right - 10), r.Next(ClientRectangle.Bottom - 20)); 
      temp.Text = "?"; 
      temp.Width = 10; 
      temp.Height = 10; 
      temp.ForeColor = System.Drawing.Color.Blue; 
      temp.BackColor = System.Drawing.Color.White; 
      Controls.Add(temp); 
      temp.Visible = true; 
      temp.Show(); 
      bluedot.Add(temp); 
     } 
    } 
} 

public class RedDot:Dot 
{ 
    public List<Label> reddot = new List<Label>(); 
    Random r = new Random(); 

    public void createdot(Rectangle Clientrectangle,Control.ControlCollection Controls) 
    { 
     for (int z = 0; z < 10; z++) 
     { 
      var temp2 = new Label(); 

      temp2.Location = new Point(r.Next(Clientrectangle.Right - 10), r.Next(Clientrectangle.Bottom - 20)); 
      temp2.Text = "?"; 
      temp2.Width = 10; 
      temp2.Height = 10; 
      temp2.ForeColor = System.Drawing.Color.Red; 
      temp2.BackColor = System.Drawing.Color.White; 
      Controls.Add(temp2); 
      temp2.Show(); 
      reddot.Add(temp2); 
     } 
    } 

他们在这里被称为

BlueDot bdot = new BlueDot(); 
     RedDot rdot = new RedDot(); 
private void Form1_Load(object sender, EventArgs e) 
{ 
    this.Activate(); 
    bdot.createdot(this.ClientRectangle,this.Controls); 
    rdot.createdot(this.ClientRectangle, this.Controls);  
} 

为什么即使循环执行10次迭代,我也只能得到5个红点?

这里是样本输出https://www.facebook.com/photo.php?fbid=2372861522202&set=a.1600508493859.85328.1270463960&type=1,我只是无法弄清楚发生了什么事等5个红点,应该是10个红点....

+0

请格式化您的问题;请参阅http://stackoverflow.com/editing-help – BoltClock

+1

它的正常前缀接口名称与“I”,以表明它们是一个接口,所以例如,通常在名称中使用名称'IDOT'而不是'Dot'以上。 – Justin

+3

bdot和rdot如何初始化? –

回答

2

这里没有继承问题。问题是随机数发生器。

尝试这一行代码:

temp2.Location = new Point(10 * z, 10 * z); 

更换

temp2.Location = new Point(r.Next(Clientrectangle.Right - 10), r.Next(Clientrectangle.Bottom - 20)); 

你会看到你的5蓝 - 标签和你的10个红色 - 标签

“?” “?”

解决随机数字发生器的弱点问题试试播种你的随机数字发生器。例如:

Random r = new Random((int)DateTime.Now.Ticks); 
+0

反正z是什么? – jeo

+0

@jeo检查您的代码! z是for循环中的变量。 – tzup

+0

我现在看到了我的10个红点......但是......它的对角位置,我需要它被分散...... – jeo

0

我并不知道,但为什么没有你让你的temp2可见?

temp2.​​Visible =真

如果这dowsn't工作,你可以同时提供您的输出的屏幕截图。有时由于窗口的大小,一个点可能会位于另一个点上。我的意思是他们确实重叠。看到你的输出可能有助于理清你的问题

+0

如何发布图像/截图? ?? – jeo

+0

这不是问题,它的输出,我不知道什么是错误的输出 – jeo

+0

现在得到了图片先生。看看 – jeo