C#中的对象数组 [英] Array of Objects in C#

查看:109
本文介绍了C#中的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在为我的编程工作而苦苦挣扎.我们必须使用C#中的动画和图形来证明科学原理.我希望保持动量或布朗运动,并且要么需要移动2d球",从墙"弹起并彼此碰撞...如此类似的代码.
我决定创建一个Particle类,并使用for循环实例化n个粒子的数组,每个粒子具有随机的x和y起始值.
这部分似乎已起作用了.至少可以编译.
但是,我无法以我认为可以的方式访问我的粒子数组的参数:
例如

Hi,
I''m struggling with my programming assignment. We have to use animation and graphics in C# to demonstrate a scientific principle. I was hoping to do either conservation of momentum or Brownian motion, and either would need 2d ''balls'' moving, bouncing off the ''walls'' and colliding with each other...so similar code.
I decided to create a Particle class, and use a for loop to instantiate an array of n Particles, each with random x and y starting values.
This part seems to have worked. At least it compiles.
However, I''m not able to access parameters of my Particles array in the way in which I thought I would be able to:
e.g.

//particlesArray is 8 by 1000 array of doubles
//numParticles is previously declined public int and equals 100;
int i;
int xValue;
int yValue;
xValue=Convert.ToInt32(particlesArray[i].x); //this part doesn''t work
yValue=Convert.ToInt32(particlesArray[i].y); //this part doesn''t work either
// I get the error "The name particles Array does not exist in the current context."


:sigh:
有人可以帮我吗?
参见下面的完整代码:


:sigh:
Could anybody help me please?
See full code below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace ParticleBox
{
    public partial class ParticleBoxForm : Form
    {
        public ParticleBoxForm()
        {
            InitializeComponent();
        }
        int numParticles = 100;
        private Thread trd;
        Graphics g = null;
        Brush myBlackBrush = new SolidBrush(Color.Black);
        int count;

        public void initializeParticlesArray()
        {
            int i;
            Random xRandom = new Random();
            Random yRandom = new Random();
            Random dXRandom = new Random();
            Random dYRandom = new Random();
            int G; // used for testing only, see below.
            Particle[] particlesArray = new Particle[numParticles];
            for (i = 0; i < numParticles; i++)
            {
                particlesArray[i] = new Particle(1.0, 1.0, xRandom.Next(0, particlePictureBox.Width), yRandom.Next(0, particlePictureBox.Height), dXRandom.Next(-1, 1), dYRandom.Next(-1, 1), 0.0, 0.0);
                G = Convert.ToInt32(particlesArray[0].x); // this is here as a test only. It appears to work (no error or red underlines etc.)
            }
        }

        private void ThreadTask()
        {
            int i;
            initializeParticlesArray();
            while (true)
            {
                g = particlePictureBox.CreateGraphics();
                g.Clear(Color.White);
                for (i = 0; i < numParticles; i++)
                {
                    DrawCircle(Convert.ToInt32(particlesArray[i].X), Convert.ToInt32(particlesArray[i].Y), Convert.ToInt32(particlesArray[i].size));
                    ///////////////////////////////////////////
                    //Why can''t my array of objects be seen by DrawCircle?

                    Thread.Sleep(10);
                }
            }
        }
        public void DrawCircle(int x, int y, int size)
        {
            Rectangle myRectangle = new Rectangle(x, y, size, size);
            g.FillPie(myBlackBrush, myRectangle, 0, 360);
        }
        private void startButton1_Click(object sender, EventArgs e)
        {
            startButton1.Text = "Start";
            trd = new Thread(new ThreadStart(this.ThreadTask));
            trd.IsBackground = true;
            trd.Start();
        }
        private void particlePictureBox_Paint(object sender, PaintEventArgs e)
        {
        }
        private void stopButton1_Click(object sender, EventArgs e)
        {
            if (trd.IsAlive)
            {
                trd.Abort();
            }
            else
                return;
        }
        private void pauseButton1_Click(object sender, EventArgs e)
        {
            if (trd.IsAlive)
            {
                trd.Suspend();
                startButton1.Text = "Resume";
            }
            else
                return;
        }
        private void numParticlesComboBox1_TextUpdate(object sender, EventArgs e)
        {
            numParticles = Convert.ToInt32(numParticlesComboBox1.Text);
        }
        public class Particle
        {
            public double size = 1.0, mass = 1.0, x = 0.0, y = 0.0, dX = 1.0, dY = 0.0, dPrevX = 0.0, dPrevY = 0.0;
            Random myRandom = new Random();
            bool moving = true;
            private Random xRandom;
            private Random yRandom;
            //bool collide = false; //use for colision handling
            public Particle(double pSize, double pMass, double pX, double pY, double dPX, double dPY, double dPrevPX, double dPrevPY)
            {
                mass = pMass;
                size = pSize;
                x = pX;
                y = pY;
                dX = dPX;
                dY = dPY;
                dPrevX = dPrevPX;
                dPrevY = dPrevPY;
            }
        }
        /*public double xMove()
        {
            if (moving == true)
            {
                x += dX;
                if (x < 0 || x > 600)
                {
                    x *= -1;
                }
                return x;
            }
            else
                return x;
        }
        public double yMove()
        {
            if (moving == true)
            {
                y += dY;
                if (y < 0 || y > 270)
                {
                    y *= -1;
                }
                return y;
            }
            else
                return y;
        }
         */
    }
}



在此先感谢:thumbsup :,
Pete



Thanks in advance :thumbsup:,
Pete

推荐答案

这是一个范围问题.您只能在initializeParticlesArray内部看到particlesArray,因为它是在此处声明的.您正在尝试在ThreadTask中使用它.要么更改声明的位置,要么将其传递给需要使用它的方法.
This is a scope issue. You can only see particlesArray inside initializeParticlesArray because that is where it is declared. You are attempting to use it inside ThreadTask. Either change where it is declared, or pass it around to the method that needs to use it.


谢谢.运行线程时,我仍然收到相同的NullReferenceException未处理错误.抱歉,如果我不太了解您要更改的内容.
现在的代码如下:

Thanks for that. I''m still getting the same NullReferenceException not handled error when I run my thread. Sorry if I haven''t quite understood what you meant to change.
My code as it stands now:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace ParticleBox
{
    public partial class ParticleBoxForm : Form
    {
        Particle[] particlesArray;
        int numParticles = 100;
        public ParticleBoxForm()
        {
            InitializeComponent();
            particlesArray = new Particle[numParticles];
        }
        private Thread trd;
        Graphics g = null;
        Brush myBlackBrush = new SolidBrush(Color.Black);
        Random xRandom = new Random();
        Random yRandom = new Random();
        Random dXRandom = new Random();
        Random dYRandom = new Random();
        public void initializeParticlesArray() //this is supposed to be making changes to the object "particlesArray" itself
        {
            int i;
            //define all eight parameters of each object
            for (i = 0; i < numParticles; i++)
            {
                particlesArray[i].mass = 1.0; //this line generates a NullException when initializeParticlesArray(ref particlesArray) is called
                particlesArray[i].size = 10.0;
                particlesArray[i].x = xRandom.Next(0, particlePictureBox.Width);
                particlesArray[i].y = xRandom.Next(0, particlePictureBox.Height);
                particlesArray[i].dX = dXRandom.Next(-1, 1);
                particlesArray[i].dY = dYRandom.Next(-1, 1);
                particlesArray[i].prevDX = 0.0;
                particlesArray[i].prevDX = 0.0;
            }
            return;
        }
        private void ThreadTask()
        {
            initializeParticlesArray(); // is this correct usage?
            /* //I commented this section out until I fix initialization problems
            while (true)
            {
                g = particlePictureBox.CreateGraphics();
                g.Clear(Color.White);
                for (i = 0; i < numParticles; i++)
                {
                    DrawCircle(Convert.ToInt32(particlesArray[i].x), Convert.ToInt32(particlesArray[i].y), Convert.ToInt32(particlesArray[i].size));
                    Thread.Sleep(10);
                }
            }
             */
        }
        public void DrawCircle(int x, int y, int size)
        {
            Rectangle myRectangle = new Rectangle(x, y, size, size);
            g.FillPie(myBlackBrush, myRectangle, 0, 360);
        }
        private void startButton1_Click(object sender, EventArgs e)
        {
            startButton1.Text = "Start";
            trd = new Thread(new ThreadStart(this.ThreadTask));
            trd.IsBackground = true;
            trd.Start();
        }
        private void particlePictureBox_Paint(object sender, PaintEventArgs e)
        {
        }
        private void stopButton1_Click(object sender, EventArgs e)
        {
            if (trd.IsAlive)
            {
                trd.Abort();
            }
            else
                return;
        }
        private void pauseButton1_Click(object sender, EventArgs e)
        {
            if (trd.IsAlive)
            {
                trd.Suspend();
                startButton1.Text = "Resume";
            }
            else
                return;
        }
        private void numParticlesComboBox1_TextUpdate(object sender, EventArgs e)
        {
            numParticles = Convert.ToInt32(numParticlesComboBox1.Text);
        }
        public class Particle
        {
            public double size = 1.0, mass = 1.0, x = 0.0, y = 0.0, dX = 1.0, dY = 0.0, prevDX = 0.0, prevDY = 0.0;
            Random myRandom = new Random();
            //bool moving = true;
            //bool collide = false; //use for colision handling
            public Particle(double pSize, double pMass, double pX, double pY, double dPX, double dPY, double prevDPX, double prevDPY)
            {
                mass = pMass;
                size = pSize;
                x = pX;
                y = pY;
                dX = dPX;
                dY = dPY;
                prevDX = prevDPX;
                prevDY = prevDPY;
            }
        }
        private void applyButton1_Click(object sender, EventArgs e)
        {
        }
    }
}


我正在使用它!感谢Anandtech论坛上的MSCoder610-编程 http://forums.anandtech.com/showthread.php?p = 30905770#post30905770 [ ^ ]


如果您仍然遇到NullReferenceException:
当声明一个对象数组(而不是像int这样的基元)时,仍然仍然需要为每个单独的元素创建对象.所以:"
I have it working! Thanks to MSCoder610 over at Anandtech Forums - Programming http://forums.anandtech.com/showthread.php?p=30905770#post30905770[^]


"If you''re still hitting the NullReferenceException:
When you declare an array of objects (rather than primitives like int), you still need to create the object for each individual element too. So:"
particlesArray = new Particle[numParticles];
for (int i=0; i<numparticles;>{
  particlesArray[i] = new Particle(...);
}
// use particlesArray



我现在有一个应用程序,可以在随机的x和y位置成功生成n个粒子,每个粒子具有不同的随机dX和dY起始值.开始动画! :laugh:



I now have an app that successfully generates n particles at random x and y positions, each with different random dX and dY starting values. On to animation! :laugh:


这篇关于C#中的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆