Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

c# - 基本数学程序引发系统空异常(Basic Math program throws system null exception)

Here is a basic math programm in which all I simply want to do is save these values num1 and num2 into the list saved within the class.

(这是一个基本的数学程序,其中我仅想做的就是将这些值num1num2保存到该类中保存的列表中。)

This keeps throwing this error when the program gets to the line in which it is added.

(当程序到达添加它的行时,这总是抛出此错误。)

System.NullReferenceException: 'Object reference not set to an instance of an object.'

(System.NullReferenceException:'对象引用未设置为对象的实例。)

I know that what I have done wrong is something obvious but I am not sure at the moment.

(我知道我做错了什么是显而易见的,但目前还不确定。)

class Program
{
    static void Main(string[] args)            
    {
        PromptAndAddUserNums();
    }

    public static void PromptAndAddUserNums() {
        bool goToken = true;
        UserInfo userInfo = new UserInfo();

        while (goToken)
        {
            Console.WriteLine("insert 1st number");
            int num1 = int.Parse(Console.ReadLine());

            Console.WriteLine("insert 2nd number");
            int num2 = int.Parse(Console.ReadLine());

            userInfo.NumList.Add(num1);
            userInfo.NumList.Add(num2);

            Console.WriteLine("do you wanna add another number?(yes or no)");
            string userChoice = Console.ReadLine().ToUpper();

            if (userChoice == "YES")
            {
                continue;
            }
            else if (userChoice == "NO")
            {
                goToken = false;
            }
        }
    }
}

class UserInfo{    
    public  List<int> NumList  { get; set; }
    public UserInfo()
    {
    }
}
  ask by Henry Peters translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you create a variable that has a type of some class, it has a default value of null as it's a reference type.

(创建具有某种类类型的变量时,由于它是引用类型,因此其默认值为null 。)

You should initialize it with the new keyword.

(您应该使用new关键字对其进行初始化。)

Like what you did with:

(就像您所做的那样:)

UserInfo userInfo = new UserInfo();

You should do the same with the List<int> , the best place in my opinion would be in the constructor:

(您应该对List<int>进行相同的操作,我认为最好的位置是在构造函数中:)

public UserInfo()
{
    NumList = new List<int>();
}

This way, when you create a new UserInfo object, the constructor is called and NumList would be initialized to a new List().

(这样,当您创建新的UserInfo对象时,将调用构造函数,并将NumList初始化为新的List()。)

So when you do userInfoObject.NumList.Add(...) , the Add method would be appliced to an initialized List, instead of null.

(因此,当您执行userInfoObject.NumList.Add(...)Add方法将应用于初始化的List,而不是null。)


Edit based on Jon Skeet comment:

(根据Jon Skeet的评论进行编辑:)

You can use the C# 6 feature called Auto-property initializer to give an initial value for your property.

(您可以使用称为自动属性初始化程序的C#6功能为属性提供初始值。)

Also it seems that you don't need a setter for your property, so you can do it like:

(同样,您似乎不需要财产的二传手,所以您可以像这样:)

public List<int> NumList { get; } = new List<int>();

Some comments NOT related to your problem:

(一些与您的问题无关的评论:)

  • Be consistent in your coding-style, you're using allman braces (ie, put braces on newlines) everywhere except for PromptAndAddUserNums and UserInfo class.

    (为保持编码风格的一致性,除PromptAndAddUserNumsUserInfo类外, PromptAndAddUserNums地方都使用allman括号(即,将括号放在换行符上)。)

  • I'd use implicitly typed local variables if the type is obvious from the assignment.

    (如果类型在赋值中很明显,我将使用隐式类型的局部变量 。)

    ( var userInfo = new UserInfo(); instead of UserInfo userInfo = new UserInfo(); )

    (( var userInfo = new UserInfo();而不是UserInfo userInfo = new UserInfo(); ))

  • I don't think you really need a boolean goToken, I'd simplify the code to be like the following:

    (我不认为您真的需要布尔goToken,而是将代码简化如下:)

     class Program { static void Main(string[] args) { PromptAndAddUserNums(); } public static void PromptAndAddUserNums() { var userInfo = new UserInfo(); while (true) { Console.WriteLine("insert 1st number"); int num1 = int.Parse(Console.ReadLine()); Console.WriteLine("insert 2nd number"); int num2 = int.Parse(Console.ReadLine()); userInfo.NumList.Add(num1); userInfo.NumList.Add(num2); Console.WriteLine("do you wanna add another number?(yes or no)"); string userChoice = Console.ReadLine().ToUpper(); if (userChoice == "NO") { break; } } } } class UserInfo { public List<int> NumList { get; } = new List<int>(); } 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...