简体   繁体   English

Null 参考 c#

[英]Null reference c#

Im writing a code where you can search a name and the subjects teaches will pop-up etc..我正在编写一个代码,您可以在其中搜索名称,然后会弹出所教的科目等。

however I'm not really sure why but i'm getting Object reference not set to an instance of an object error im missing something i know, can someone help me?但是我不太确定为什么,但我得到Object 参考未设置为 object 错误的实例我缺少我知道的东西,有人可以帮我吗? i tried different methods didn't really work... heres my code:我尝试了不同的方法并没有真正起作用......这是我的代码:

public partial class MainWindow : Window
    {
        Course my = new Course();
        public class Course
        {

            public string[] Name { get; set; }
            public string[] Subject { get; set; }
            public string[] Hour { get; set; }

            public Course(string[] name, string[] subject, string[] hour)
            {
                this.Name = name;
                this.Subject = subject;
                this.Hour = hour;

            }
        }

        public MainWindow()
        {
            InitializeComponent();


            my.Name[0] = "Ali";
            my.Name[1] = "Sefer";

            my.Subject[0] = "INFORMATIKA";
            my.Subject[1] = "ENGLISH";

            my.Hour[0] = "12";
            my.Hour[1] = "22";

        }

        private void searchButton_Click(object sender, RoutedEventArgs e)
        {
            Find();
        }


        private void Find()
        {

            int index = 0;
            string wanted = wantedName.Text;

            while (my.Name[index] != wanted && (my.Name[index] != "END"))
            {
                index++;
            }
            if (my.Name[index] == wanted)
            {
                outputLabel.Content = " " + my.Name[index] + " "  + my.Subject[index];
            }
            else
            {
                outputLabel.Content = "Name not found";
            }
        }


    }
}

You are using arrays without initializing them.您正在使用 arrays 而不初始化它们。 While you have defined a constructor for your Course class that takes values for the arrays, you are using the default constructor.虽然您已经为Course class 定义了一个构造函数,该构造函数采用 arrays 的值,但您使用的是默认构造函数。 Try calling your own constructor with arguments like尝试使用 arguments 调用您自己的构造函数

Course my = new Course(new string[2], new string[2], new string[2]);

Before you can assign a value to an element like my.Name[0] , you have to ensure that my.Name is referencing an allocated array, which means there is memory available for your elements.在您可以为my.Name[0]类的元素分配值之前,您必须确保my.Name引用的是分配的数组,这意味着您的元素有 memory 可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM