2009-11-20 7 views
0

나는 5 개의 문자열이 들어있는 ArrayList가있는 숙제 프로젝트를 진행하고 있습니다. ArrayList (인덱스 값 사용) 항목을 선택하는 방법은 알고 있지만 객체 문자열에 액세스하는 방법은 알지 못합니다. 어떤 도움이라도 좋을 것입니다. 배열 목록의 모든 항목이의 얼굴에 "객체"하지만, 실제로 내부적으로 장비 객체있어 이후ArrayList에 포함 된 개체 선택

private ArrayList myComponents; 

private int listIndex = 0; 

myComponents = new ArrayList(); //Arraylist to hold catalog data 

equipment = new Equipment(itemName, itemType, itemDetails, itemMaintenance, itemId); 

myComponents.Add(equipment); 

// class file is called Equipment.cs 

// I know normally that equipment without the arraylist this would work: 
// equipment.getitemName(); 
// but combining with the arraylist is being problematic. 
+0

여기에서 "IndexOf"또는 "Contains"방법이 필요하지 않은 이유는 무엇입니까? –

답변

0

, 당신은 방법이 필요합니다 : 여기 내가 시도한 것입니다 ArrayList에서 항목을 검색 할 때 객체에서 장비로 이동하는 것 (힌트 : 캐스트). 이것이 숙제이기 때문에 그것을 버리고 싶지는 않지만 도움이된다면 ....

+0

이것은 C#이기 때문에 (객체) 캐스트 유형을 사용하지 마십시오. 당신이 사용해야하는 또 다른 키워드가 있습니다. – Woot4Moo

1

ArrayList 대신 List를 사용하는 것이 나을 것입니다. ArrayList는 을 강력하게 타입 지정하지 않으므로 어레이 내부의 사물/물체를 "장비"처럼 취급 할 수는 없지만 일반적인 지루한 객체처럼 처리 할 수 ​​있습니다.

List<Equipment> myComponents = new List<Equipment>(); 

equipment = new Equipment(itemName, itemType, itemDetails, itemMaintenance, itemId); 

myComponents.Add(equipment); 

foreach(Equipment eq in myComponents) 
{ 
    eq.getItemName(); 
    // do stuff here 
} 

이 문제가 해결되는지 알려주세요.

1

ArrayList는 어떤 종류의 개체가 들어 있는지 알지 못합니다. 그것은 모든 것을 객체로 취급합니다. ArrayList에서 객체를 가져올 때, 반환 된 Object 참조를 해당 유형의 참조 및 해당 유형의 메소드에 액세스하기 전에 변환해야합니다. 이 작업을 수행하는 방법에는 여러 가지가 있습니다.

// this will throw an exception if myComponents[0] is not an instance of Equipement 
Equipment eq = (Equipment) myComponents[0]; 

// this is a test you can to to check the type 
if(myComponents[i] is Equipment){ 
    // unlike the cast above, this will not throw and exception, it will set eq to 
    // null if myComponents[0] is not an instance of Equipement 
    Equipment eq = myComponents[0] as Equipment; 
} 

// foreach will do the cast for you like the first example, but since it is a cast 
// it will throw an exception if the type is wrong. 
foreach(Equipment eq in myComponents){ 
    ... 
} 

가능한 경우 일반 유형을 사용하고 싶습니다. ArrayList와 가장 비슷하게 작동하는 것은 List입니다. generics는 많은 경우에 도움이되어 ArrayList 코드를 작성하고 오류가 발생하기 쉬운 모든 형 변환을 피할 수 있습니다. 물론 단점은 목록에 유형을 혼합 할 수 없다는 것입니다. List는 장비 인스턴스로 가득 찬 ArrayList가 될 동안 문자열을 넣을 수 없습니다. 해결하려는 특정 문제로 인해 어떤 것이 더 적합한 지 판단 할 수 있습니다.

관련 문제