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.
(为保持编码风格的一致性,除PromptAndAddUserNums
和UserInfo
类外, 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>(); }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…