2014-02-27 4 views
-3

텍스트 파일의 모든 입력 값을 저장할 수있는 목록을 만들었습니다. 이제 다른 수업에서이 목록에 액세스해야합니다. 코드가 변경해야합니까?다른 클래스의 목록에 액세스하는 방법

public static void boxdetails() 
{ 
    String line; 
    List<Box> listofboxes = new List<Box>(); 
    try 
    { 
     using (StreamReader sr = new StreamReader("c:/boxvalues.txt")) 

     while ((line = sr.ReadLine()) != null) 
     { 
      // create new instance of container for each line in file 
      Box box = new Box(); 
      // List<Box> listofboxes = new List<Box>(); 
      string[] Parts = line.Split(' '); 
      // set non-static properties of container 
      box.bno = Parts[0]; 
      box.length = Convert.ToDouble(Parts[1]); 
      box.height = Convert.ToDouble(Parts[2]); 
      box.depth = Convert.ToDouble(Parts[3]); 
      box.volume = Convert.ToDouble(Parts[4]); 
      box.placed = Convert.ToBoolean(Parts[5]); 
      // add container to list of containers 

     } 
     listofboxes.Add(box); 
     Console.WriteLine((box.bno) + "is ADDED"); 
     listofboxes = listofboxes.OrderBy(x => x.volume).ToList(); 
    } 
    //[code incomplete] 

답변

1

1 단계 :public 액세스 한정자와 방법 밖에 List<Box>를 선언합니다.

class ClassA 
{ 
    public List<Box> myList = new List<Box>(); 
} 

2 단계 : 액세스하여 List<Box> 다른 클래스에서 해당 클래스의 인스턴스 변수.

class ClassB 
{ 
ClassA aRef=new ClassB(); 
aRef.myList.Add(myBox);//access here 
} 
0

시도는이 같은 멤버 속성 listofboxes을 만들기 : 당신이 어떤에서 액세스 할 수 있도록, 정적으로

while ((line = sr.ReadLine()) != null) 
{ 
    // create new instance of container for each line in file 
    Box box = new Box(); 

    // List<Box> listofboxes = new List<Box>(); 
    string[] Parts = line.Split(' '); 

    // set non-static properties of container 
    box.bno = Parts[0]; 
    box.length = Convert.ToDouble(Parts[1]); 
    box.height = Convert.ToDouble(Parts[2]); 
    box.depth = Convert.ToDouble(Parts[3]); 
    box.volume = Convert.ToDouble(Parts[4]); 
    box.placed = Convert.ToBoolean(Parts[5]); 

    // add container to list of containers 
    this.ListOfBoxes.Add(box); 
} 
0

선언 목록 :

public List<Box> ListOfBoxes 
{ 
    get 
    { 
     return this._listOfBoxes; 
    } 
    set 
    { 
     this._listOfBoxes = value; 
    } 
} 
private List<Box> _listOfBoxes = new List<Box>(); 

는 다음과 같이 코드를 변경 클래스 명을 사용하는 클래스

like,

ClassName.listofboxes //assign to some other list or use as per ur need 

.....

public static List<Box> listofboxes; 
public static void boxdetails() 
{ 
    listofboxes = new List<Box>(); 
    ... 
} 
관련 문제