2014-01-29 3 views
0

이 게시물은 다른 게시물과 비슷할 수 있습니다. 그러나 여기에서 내가 잘못하고있는 것이 확실하지 않습니다. 참고로, 나는 프로그래밍에 익숙하지 않고 여전히 올바른 흐름을 배우려고 노력하고있다.Null 참조 예외 처리되지 않았습니다. C# 콘솔 응용 프로그램

다음은 코드입니다. 예외는 "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

안녕하세요. 귀하의 질문에 스택 추적 예외를 추가 할 수 있습니까? –

+0

루프의 반복은 어떤 일이 발생합니까? 나는 'i'의 가치는 무엇입니까? – pamphlet

답변

5

친구 배열이 초기화되지 않았습니다. 따라서 MyFriends[i]은 널 참조를 히트합니다. 이는 존재하지 않는 것을 액세스하려는 다른 방법입니다.

즉, 친구 2 명을위한 슬롯이있는 Array이지만 두 슬롯은 모두 비어 있습니다.

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 
} 

그리고 일이 잘 될 것입니다 : 당신이 그들의 속성을 사용하기 전에 당신은 여전히 ​​등

Phone는 단순히 for 루프 다음과 같이 시작, 각 슬롯에 친구가 같은 Name이 필요합니다. 이렇게하면 사용하려는 슬롯에 친구를 추가하게됩니다.

+1

설명해 주셔서 감사합니다. 완벽하게 작동합니다! –

1

두 개의 요소가있는 배열을 만들었지 만 요소를 임의의 값으로 설정했습니다. 그들은 모두 null 있습니다 : 어레이에서 MyFriends[i]를 사용하려고하면, 그래서

static public Friend[] MyFriends = new Friend[2]; 

, 당신은 실제로 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(); 

    // ... 
0

MyFriends는 Friend 클래스의 배열입니다. 배열의 각 요소는 friend 생성자로 초기화해야 메모리에 할당됩니다.

1

컬렉션을 만들 때 목표 유형의 기본값으로 채워지고 null 인 경우 모든 참조 유형의 기본값이 채워집니다. 따라서 문제를 해결하려면 배열에있는 항목을 초기화해야만 액세스 할 수 있습니다.

.... 
for (int i = 0; i < 2; ++i) 
{ 
    MyFriends[i] = new Friend(); 
    ... 
관련 문제