使用接口派生类问题

时间:2011-09-07 10:37:08

标签: c# winforms visual-studio windows-7

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个红点....

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

我不确定,但为什么不让你的temp2可见????

temp2.​​Visible =真

如果此功能不起作用,您可以提供两个输出的屏幕截图。有时由于窗口的大小,一个点可能位于另一个点上。我的意思是他们实际重叠。查看输出可能有助于解决您的问题