2014-07-18 2 views
0

"knownSolarSystems"라는 배열의 모든 객체를 "확인"하려고합니다. 그러나 정의 때문에 모든 배열 슬롯이 설정됩니다. 내가 배열의 첫 번째 (0 번째?) 슬롯에 붙여 넣은 CSolarSystem 클래스의 객체를 생성보다도 C# 배열의 슬롯이 클래스 객체로 채워 졌는지 확인합니다.

CSolarSystem[] knownSolarSystems; 
public void Start() { 
    knownSolarSystems = new CSolarSystem[10]; 
    knownSolarSystems[0] = new CSolarSystem(); 
} 

(적어도 비어 lels 아니다). (knownSolarSystems [0])

비록 하나의 객체를 가지고 있어도, foreach 루프는 아직 정의되지 않은 몇 가지 객체에 접근하려고하기 때문에 에러를 내고 있습니다.

이것은 foreach 루프입니다 :

foreach(CSolarSystem solarSystem in knownSolarSystems) { 
    solarSystem.Update(); 
} 

는 그리고 이것은 오류입니다 :

NullReferenecException: Object reference not set to an instance of an object CUniverse.Update() 

그래서이 채워지지 않는 그 슬롯을 "생략"하는 방법이있다? 안부와

, deSpeach

+3

'Where'를 사용하여'null '값을 건너 뛰는 것 외에 길이 10의 배열로 이것을 초기화해야합니까? 대신'List '을 사용할 수 있습니까? –

+0

내가 원했지만 효과적으로 사용하는 방법을 모르므로 배열을 사용합니다. – user3783593

+0

실제로 List는 인데 여기서 T는 CSolarSystem입니다. 이렇게하면 얼마나 많은 객체를 처리해야하는지 손에서 미리 알아야 할 필요가 없습니다. 물론 태양계에 얼마나 많은 객체가 있는지 알면 배열을 사용하고 http://astronomy.stackexchange.com/에서 결과를 게시 할 수 있습니다. -) – Steve

답변

2

So is there a method to "skip" those slots which aren't filled?

당신은 단순히 (null)를 확인할 수 있습니다 :

foreach(CSolarSystem solarSystem in knownSolarSystems.Where(s => s != null)) { 
    solarSystem.Update(); 
} 

참고 파일 상단에 using System.Linq을 추가해야합니다.

물론
List<CSolarSystem> knownSolarSystems = new List<CSolarSystem>(); 

public void Start() { 
    knownSolarSystems.Add(new CSolarSystem()); 
} 
+0

그것은 "어디서"에 대한 정의가 없다는 오류를 준다. – user3783593

+0

'using System.Linq'을 추가해야하는데, 내 대답을 편집했다. –

3

사용 Where 값을 제거하기 : 그것은 아직 초기화되어 있지 않은 경우

foreach(CSolarSystem solarSystem in knownSolarSystems.Where(x => x != null)) 
{ 
    solarSystem.Update(); 
} 
2

: 슬롯가 작성되어 있는지 확인하고, 그렇지 않은 경우, 그것을 이동

다른 방법은 증가 될 수있는 배열 대신 List<T>을 사용하는 것이다.

foreach(CSolarSystem solarSystem in knownSolarSystems) { 
    if (solarSystem == null) continue; 
    solarSystem.Update(); 
} 

null 테스트

은 다른 사람들이 쇼를 게시 LINQ 버전으로 주위를 이동할 수 있습니다.

+0

오 고마워요 :) – user3783593

+0

하지만이 하나도 채워진 배열을 건너 뜁니다 D : – user3783593

관련 문제