Null Reference Exception是未处理的C#控制台应用程序

Lar*_*y B 0 c# class

我知道这可能与其他一些帖子类似,但我不太清楚我在这里做错了什么.作为一个FYI,我是编程的新手,仍然在努力学习正确的流程.

这是代码,例外情况发生在"MyFriends [i] .Name = friendName".

using System;
using System.Collections;

namespace FriendList
{
    class FriendList
    {
        static public Friend[] MyFriends = new Friend[2];
        public static void Main()
        {
            string friendName;
            string friendPhone, friendMonth, friendDay, friendYear;
            int intMonth, intDay, intYear;

            for (int i = 0; i < 2; ++i)
            {
                Console.Write("enter name");
                friendName = Console.ReadLine();
                MyFriends[i].Name = friendName;

                Console.Write("phone");
                friendPhone = Console.ReadLine();
                MyFriends[i].Phone = friendPhone;

                Console.WriteLine("Enter Month: ");
                friendMonth = Console.ReadLine();
                intMonth = Convert.ToInt32(friendMonth);
                MyFriends[i].Month = intMonth;

                Console.WriteLine("Enter Day: ");
                friendDay = Console.ReadLine();
                intDay = Convert.ToInt32(friendDay);
                MyFriends[i].Day = intDay;

                Console.WriteLine("Entery Year: ");
                friendYear = Console.ReadLine();
                intYear = Convert.ToInt32(friendYear);
                MyFriends[i].Year = intYear;
            }

            for (int i = 0; i < 2; ++i)
            {
                string information = string.Format("first name: {0}, phone {1}", MyFriends[i].Name, MyFriends[i].Phone);
                Console.WriteLine(information);
            }
            Console.Read(); 
        }
    }

    class Friend
    {
        string _Name = string.Empty, _Phone = string.Empty;
        int _Day = 0, _Month = 0, _Year = 0;

        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        public string Phone
        {
            get { return _Phone; }
            set { _Phone = value; }
        }

        public int Month
        {
            get { return _Month; }
            set { _Month = value; }
        }

        public int Day
        {
            get{ return _Day; }
            set{ _Day = value ; }
        }

        public int Year
        {
            get { return _Year;}
            set { _Year = value; }
        }

        public Friend()
        { }

    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的指导!

Ren*_*nan 5

您的好友数组初始化为空.所以MyFriends[i]会命中一个空引用,这是另一种说法是你试图访问不存在的东西.

换句话说,你有Array两个朋友的插槽,但两个插槽都是空的.你仍然需要在每个插槽的朋友才可以使用它们的属性,如Name,Phone等.

只需for像这样启动循环:

for (int i = 0; i < 2; ++i)
{
    MyFriend[i] = new Friend(); //or pass parameters as required by the constructor
    // rest of your code goes here
}
Run Code Online (Sandbox Code Playgroud)

事情会没事的.这样,您就可以将朋友添加到您将使用的插槽中.