我知道这可能与其他一些帖子类似,但我不太清楚我在这里做错了什么。作为一个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()
{ }
}
}
感谢您的指导!
答案 0 :(得分: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
}
事情会没事的。这样,您就将朋友添加到您将使用的插槽中。
答案 1 :(得分:1)
您已经创建了一个包含两个元素的数组,但您已将元素设置为任何值。它们都是null
:
static public Friend[] MyFriends = new Friend[2];
因此,当您尝试使用数组中的MyFriends[i]
时,实际上是null
。
MyFriends[i].Name = friendName;
您的NullReferenceException
来自哪里。
您必须初始化阵列的成员。例如:
for (int i = 0; i < MyFriends.Length; i++)
{
// Put a new Friend object in the array.
MyFriends[i] = new Friend();
// ...
答案 2 :(得分:1)
创建集合时,它们会填充目标类型的默认值,以及null
的任何引用类型的默认值。因此,要解决您的问题,您必须在访问它们之前初始化数组中的项目:
....
for (int i = 0; i < 2; ++i)
{
MyFriends[i] = new Friend();
...
答案 3 :(得分:0)
MyFriends是一群朋友级。 数组中的每个元素都需要用友元构造函数初始化,因此它将被分配一个内存。