2016-10-03 2 views
-2

나는 Inheritance을 사용하려고 시도했지만 작동하지 않으므로 더구나 Composition을 사용해 보았지만 똑같이 작은 succes를 사용했습니다. 개별 배열은 특정 파일을 만드는 텍스트 파일에서 읽습니다.한 클래스에서 생성 된 변수를 다른 클래스에서 생성하려면 어떻게합니까?

The generating code: 
public static void ReadText(string[] args) 
    { 
     Dictionary<string, int[]> rows = new Dictionary<string, int[]>(); 

     string[] lines = File.ReadAllLines("txt.txt"); 

     int counter = 0; 

     foreach (string s in lines) 
     { 
      //Console.WriteLine(s); 
      string[] arr = s.Split(' '); 
      int[] array = new int[arr.Length]; 

      for (int i = 0; i < arr.Length; i++) 
      { 
       array[i] = Convert.ToInt32(arr[i]); 
      } 


      string key = "M_array_" + counter++; 
      rows.Add(key, array); 
      //ShowArray(array); 

     } 

     foreach (string key in rows.Keys) 
     { 
      Console.WriteLine($"{key}: {String.Join(" ", rows[key])}"); 
     } 

     Console.ReadLine(); 
    } 

어떻게 부릅니까 M_array_1, 타 클래스의 M_array_2 등을 다음과 같이 코드는? 보통 나는 내가 inheritance를 사용하는 다른 클래스에서 하나 varibel 전화 :

Class_example CE = new Class_example(); 

또는 Composition을 :

public class wheel{} 
public class car : wheel{} 
+2

왜 사전을 가지고 있는지 분명하지 않습니다 ... 다른 코드에 배열을 전달하는 것이 더 좋지 않습니까? 그러나 문제가 실제로 특정 데이터 (이 경우 배열/사전)와 관련이 있는지 또는 한 클래스에서 다른 클래스로 정보를 가져 오는 방법을 모르는 지 여부는 명확하지 않습니다. 다른 코드가 무엇인지 알 수 없으므로 까다로운 부분이 있습니다. 아마도'ReadText' 메쏘드는'int [] []'또는'List '를 돌려 주어야합니까? –

+0

귀하의 최종 의견을 통해 상속 및 구성을 판단하는 것을 확신하지 못합니다. 아마 조금 더 살펴 봐야 할 것입니다. –

답변

-1

가 다른 클래스로부터 사전 정적 및 액세스 할 수있게?

public class MyClass 
{ 
    public static Dictionary<string, int[]> Rows = new Dictionary<string, int[]>(); // initialize just in case 
    public static void ReadText(string[] args) 
    { 
     Rows = new Dictionary<string, int[]>(); 

     string[] lines = File.ReadAllLines("txt.txt"); 

     ... 
    } 
} 

public class AnotherClass 
{ 
    public void DoSomething() 
    { 
     // Make sure you have done MyClass.ReadText(args) beforehands 
     // then you can call the int array 
     int[] m_array_1 = MyClass.Rows["M_array_1"]; 
     int[] m_array_2 = MyClass.Rows["M_array_2"]; 

     // or 
     foreach (string key in MyClass.Rows.Keys) 
     { 
      Console.WriteLine($"{key}: {String.Join(" ", rows[key])}"); 
     } 
    } 
} 
+0

왜 메서드에서 데이터를 반환하지 않습니까? 이 두 단계 접근법은 오류가 발생하기 쉽습니다. 'ReadText'를 호출하고'Rows'를 호출해서는 안됩니다. –

+0

downvote 주셔서 감사합니다, 나는 단지 다른 클래스가 int 배열에 액세스 할 수 있도록하기 위해 자신의 요구 사항을 충족시키기위한 제안을하고 있습니다. – kurakura88

관련 문제