创建类实例时出现“空引用”错误问题 [英] Problem with 'Null Reference' Error while creating Class instances

查看:125
本文介绍了创建类实例时出现“空引用”错误问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将字符串转换为c#中的对象类?



我创建了一个包含字符串变量的类但是没有接受价值。



错误:对象引用未设置为对象的实例



这就是我所拥有的:



How can i convert a string to a object class in c#?

I have created a class with string variables but do not accept the value.

ERROR: Object reference not set to an instance of an object

This is what I have:

using System;

namespace movies
{
    class Program
    {
        static void Main(string[] args)
        {   

            Movie[] m1 = new Movie[10];
            int qty;

            Console.WriteLine("How many Movies you want to add?");
            qty = Convert.ToInt32(Console.ReadLine());
            
            for (int i=0; i < qty; i++)
            {                
                Console.WriteLine("Movie #{0} Title: ", i+1);
                m1[i].Title = Convert.ToString(Console.ReadLine());
                    Console.WriteLine("Movie #{0} Director: ", i+1);
                m1[i].Director = Console.ReadLine();
                Console.WriteLine("Movie #{0} Year: ", i+1);
                m1[i].Year = Convert.ToInt32(Console.ReadLine());
            }
        
        }// end of main
     }//end of class program
     
    class Movie 
    {
        string title = "V-for vendetta";
        string director = "Portman";
        int year = 2002;
        
        public string Title
        {
            set { title = value; }
            get { return title; }
        }
        
        public string Director
        {
            set { director = value; }
            get { return director; }
        }    
               
        public int Year
        {
            set { year = value; }
            get { return year; }
        }
        
        public Movie (string a, string b, int c)
        {
            Title = a;
            Director = b;
            Year = c;
        }
        
        public void print()
        {
            Console.WriteLine("Title: {0}", Title);
            Console.WriteLine("Director: {0}", Director);
            Console.WriteLine("Year: {0}", Year);
        }
    }//End of class class movies
    
    
}//end of namespace

推荐答案

问题在于您的对象,而不是字符串。当您创建数组时,您刚刚创建它,您忘记初始化数组中的对象。

The problem is with your object, not with the string. When you create the array, you just created it, you forgot to initialize the objects in the array.
Movie[] m1 = new Movie[10];



但是当你试图从中获取物品时,比如,


But when you try to access the items from it, like,

m1[i].Title = Convert.ToString(Console.ReadLine());



抛出该错误。没关系,这是预期的行为,因为您实际上没有初始化对象。 m1 ith 索引处的对象。要解决此问题,您需要初始化对象,然后继续使用代码。



请尝试使用此代码,




It throws that error. It is OK, and that is the expected behavior, because you have not actually initialized the object. The object that is at ith index in m1. To fix this problem, you would need to initialize the objects and then continue to work with the code.

Try this code instead,

for (int i=0; i < qty; i++)
{                
    if(m1[i] == null) {
        m1[i] = new Movie(); // Create the object
    }
    Console.WriteLine("Movie #{0} Title: ", i+1);
    m1[i].Title = Convert.ToString(Console.ReadLine());
    // So on...



现在,当你使用它时,它不会抛出该错误,因为该对象不再是null。当初学者尝试从他们的旅程开始时,这个NullReferenceException是一个非常基本的错误。 :-)



代码执行中的空错误是什么 [ ^ ]



编辑



如前所述,你知道,你的类中的构造函数需要三个参数,在我的代码中你需要在类中定义一个无参数构造函数。像这样,


Now, when you will use this, it won't throw that error because the object is not null anymore. This NullReferenceException is a very basic error found in programs when beginners try to start with their journey. :-)

What is a null error in code Execution[^]

Edit:

As already mentioned and you know, the constructor in your class requires three parameters, in my code you need to have a parameterless constructor defined in the class. Like this,

class Movie {
   // Fields

   public Movie() {}

   // Other constructors and functions
}



这样,上面提供的代码就能成功运行。 : - )


This way, the code provided above would work, successfully. :-)


静态数组是非常糟糕的,你假设大小将低于10但它一定不能!

将List作为动态增长容器,试试这个:



Static array is very bad, you assume the size will be under 10 but it must not!
Take the List as dynamically growing container, try this:

static void Main()
{
    //Movie[] m1 = new Movie[10];
    List<Movie> mi = new List<Movie>();
    int qty;

    Console.WriteLine("How many Movies you want to add?");
    qty = Convert.ToInt32(Console.ReadLine());

    for (int i = 0; i < qty; i++)
    {

        Console.WriteLine("Movie #{0} Title: ", i + 1);
        string sTitle = Convert.ToString(Console.ReadLine());
        Console.WriteLine("Movie #{0} Director: ", i + 1);
        string sDirector = Console.ReadLine();
        Console.WriteLine("Movie #{0} Year: ", i + 1);
        int nYear = Convert.ToInt32(Console.ReadLine());

        mi.Add(new Movie(sTitle, sDirector, nYear));

    }
}


这篇关于创建类实例时出现“空引用”错误问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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