代码优化

修改前的代码

            greyhounds[0] = new Greyhound()
            {
                StartingPosition = pictureBox2.Location.X + pictureBox2.Width,
                MyPictureBox = pictureBox2,
                RacetrackLength = (pictureBox1.Location.X + pictureBox1.Width) - (pictureBox2.Location.X + pictureBox2.Width),
                Randomizer = new Random()
            };

            greyhounds[1] = new Greyhound()
            {
                StartingPosition = pictureBox2.Location.X + pictureBox2.Width,
                MyPictureBox = pictureBox3,
                RacetrackLength = (pictureBox1.Location.X + pictureBox1.Width) - (pictureBox2.Location.X + pictureBox2.Width),
                Randomizer = new Random(10)
            };
            greyhounds[2] = new Greyhound()
            {
                StartingPosition = pictureBox2.Location.X + pictureBox2.Width,
                MyPictureBox = pictureBox4,
                RacetrackLength = (pictureBox1.Location.X + pictureBox1.Width) - (pictureBox2.Location.X + pictureBox2.Width),
                Randomizer = new Random(5)
            };

            greyhounds[3] = new Greyhound()
            {
                StartingPosition = pictureBox2.Location.X + pictureBox2.Width,
                MyPictureBox = pictureBox5,
                RacetrackLength = (pictureBox1.Location.X + pictureBox1.Width) - (pictureBox2.Location.X + pictureBox2.Width),
                Randomizer = new Random(9)
            };


修改后的代码

            PictureBox[] picureBoxes = new PictureBox[4] { pictureBox2,pictureBox3,pictureBox4,pictureBox5};
            int startPosition = pictureBox2.Location.X + pictureBox2.Width;
            int racetrackLength = (pictureBox1.Location.X + pictureBox1.Width) 
                - (pictureBox2.Location.X + pictureBox2.Width);
            for (int i = 0; i < 4; i++)
            {
                greyhounds[i] = new Greyhound() {  MyPictureBox = picureBoxes[i],
                    StartingPosition = startPosition,RacetrackLength = racetrackLength, 
                    Randomizer = new Random(i)};
                
            }


 

你可能感兴趣的:(代码优化)