2014-03-28 3 views
0

좋아, 나는 내 문제에 대해 좀 더 명확하게 다른 프로그램을 만들었습니다. int 배열을 포함하는 개체 배열이 있고 요소 뉴런 1에서 인덱스 [0]을 인쇄하려고합니다. 그러나 'Console.WriteLine (ex.neuron [0])'줄에 null 참조 예외가 발생합니다. 내 코드는 아래와 같습니다.액세스 요소 배열

static void test(object[,] array1) 
    { 
      ex ex = new ex(); 
      Console.WriteLine(ex.neuron1[0]); 
      Console.ReadLine(); 
    } 
} 

}

나는 예외가 나는 ex.neuron [0에 접근하고있다으로 발생하고 있다고 생각 :

namespace ConsoleApplication5 
    { 
class Program 
{ 

    static void Main() 

    { 
     ex ex = new ex(); 

     int[]neuron1 = new int[5]; 
     int[]neuron2 = new int[5]; 
     int[]neuron3 = new int[5]; 
     int[]neuron4 = new int[5]; 
     int[]neuron5 = new int[5]; 



     object[,] array1 = new object[2,2]; 
     array1[0, 0] = ex.neuron1; 
     neuron1[0] = 1; 

     array1[0, 1] = neuron2; 
     neuron2[1] = 1; 

     test(array1); 

    } 

    static void test(object[,] array1) 
    { 
      ex ex = new ex(); 
      Console.WriteLine(ex.neuron1[0]); 
      Console.ReadLine(); 
    } 
} 

}

나는 클래스가 점점 여기 neuron1 설정이 ] 값 1을 포함하도록 정의되기 전에. 그래서 내 질문은 ex.neuron [0]에 액세스 한 후 값 1을 보유하고있는 것으로 설정되었습니다. 감사.

+0

은 이전 수업입니까? ex ex = new ex();를 선언하십시오. 클래스와 같은 이름의 변수를 선언합니까? – Sorceri

+0

'ex '가 어떻게 구현 되었습니까? –

+0

@Sorceri 예 ex는 내가 만든 클래스이고 변수는 같은 이름입니다. 죄송합니다. 이것은 제가 만든 짧은 예일뿐입니다. – user3365114

답변

1

아마 당신은 단지 그것을 전달해야 할 때, 각 기능에 ex의 새로운 인스턴스를 생성하고 이러한 라인을

int[] neuron1 = new int[5]; 

를 교체 ex.neuron1을 설정하지 함께. 또한 인스턴스 자체에 neuron 필드를 설정하지 마십시오. 다음은 간단한 코드 버전입니다.

static void Main() 
{ 
    // define it here 
    ex ex = new ex(); 

    // initialize the neuron fields (although you should probably do this 
    // in the constructor for ex 
    ex.neuron1 = new int[5]; 
    ex.neuron2 = new int[5]; 
    ex.neuron3 = new int[5]; 
    ex.neuron4 = new int[5]; 
    ex.neuron5 = new int[5]; 

    // set some neuron array values 
    ex.neuron1[0] = 1; 
    ex.neuron2[1] = 1; 

    // pass the instance along to test 
    test(ex); 
} 

static void test(ex ex) 
{ 
    // access the array value here 
    Console.WriteLine(ex.neuron1[0]); 
    Console.ReadLine(); 
} 
1

당신은

ex.neuron1 = new int[5];