C#中的类添加错误发生 [英] Class Add in C# Error Ocure

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

问题描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Text;

namespace WindowsFormsApplication3
{
    public class Class1
    {
        public Rectangle[] Snakerec;
        public SolidBrush Brush;

        private int x, y, height, width;

        public void Snake()
        {
            Snakerec = new Rectangle[3];
            Brush = new SolidBrush(Color.Blue);

            x = 20;
            y = 0;
            height = 10;
            width = 10;

            for (int i = 0; i < Snakerec.Length; i++)
            {
                Snakerec[i] = new Rectangle(x, y, width, height);
                x -= 10;
            }
        }
        public void Drawsnake(Graphics paper)
        {
            try
            {
                foreach(Rectangle rec in Snakerec)
                {
                    paper.FillRectangle(Brush, rec);
                }
            }
            catch (Exception ex)
            {
                string st = ex.Message;

            }
        }
    }
}


我用C语言编写此代码,在运行时出现此错误,
错误是对象引用未设置为对象的实例" ,,,


i write this code in C sharp this error occur in Runtime,,
And Error is "Object reference not set to an instance of an object",,,

推荐答案

您没有显示构造函数,但我假设您没有在调用DrawSnake方法之前,不要调用Snake方法.
在尝试使用foreach之前,请确保已执行操作,或向DrawSnake添加一些防御性代码以确保Snakerec不为null.
You don''t show the constructor, but I assume that you aren''t calling the Snake method before you call the DrawSnake method.
Either make sure you do, or add some defensive code to DrawSnake to ensure that Snakerec is not null before you try to use the foreach.


这篇关于C#中的类添加错误发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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