2010-12-22 2 views
1

기본 질문의 비트 제가 생각하기에 객체가 A 또는 B 유형의 다른 객체를 소유하고 싶다면 객체를 사용하는 응용 프로그램이 특정 속성에 어떻게 액세스 할 수 있습니까? 예 :추상 객체에 대한 구체적인 속성에 액세스하고 있습니까?

public abstract class Animal 
{ 
    private int Age; 
    // Get Set 
} 

public class Tiger: Animal 
{ 
    private int NoStripes; 
    // Get Set 
} 

public class Lion : Animal 
{ 
    private bool HasMane; 
    // Get Set 
} 

public class Zoo 
{ 
    private Animal animal; 
    // Get Set 
} 

public static void Main() 
{ 
    Zoo zoo = new Zoo(); 
    zoo.animal = new Tiger(); 

    // want to set Tiger.NoStripes 
} 

답변

0

이것은 상속 및 다형성의 요지입니다. 당신이 동물의 인스턴스가 실제로 호랑이의 인스턴스 인 것으로 판단 할 수있는 경우

, 당신은 그것을 캐스팅 할 수 있습니다

((Tiger)zoo.Animal).NoStripes = 1; 

을하지만, 당신이하려고하면 외설 동물의 인스턴스에서이 작업을 수행 할 Tiger, 런타임 예외가 발생합니다. 예를 들어

:

Zoo zoo = new Zoo(); 
zoo.animal = new Tiger(); 
((Tiger)zoo.Animal).NoStripes = 1; //Works Fine 

((Lion)zoo.Animal).NoStripes = 1; //!Boom - The compiler allows this, but at runtime it will fail. 

사용하여 다른 주조 구문이있는 캐스트가 실패 할 경우 대신 예외, null를 돌려줍니다 키워드 "로". 이것은 훌륭하게 들리지만 실제로는 null 객체가 소비 될 때 미묘한 버그가 발생할 가능성이 높습니다.

Tiger temp = zoo.Animal as Tiger; //This will not throw an exception 
temp.NoStripes = 1; //This however, could throw a null reference exception - harder to debug 
zoo.Animal = temp; 

, 당신은,

Tiger temp = zoo.Animal as Tiger; //This will not throw an exception 
if (temp != null) 
{ 
    temp.NoStripes = 1; //This however, could throw a null reference exception - harder to debug 
    zoo.Animal = temp; 
} 
2

당신은 Tiger

zoo.Animal 캐스팅해야합니다 또는 당신이 직접 대답에 이것에 대한 물론

public static void Main() { 
    Zoo zoo = new Zoo(); 
    zoo.animal = new Tiger(); 

    ((Tiger)zoo.Animal).NoStripes = 10; 
} 

을하는 것입니다

public abstract class Animal 
{ 
    public int Age; 
    // Get Set 
} 

public class Tiger : Animal 
{ 
    public int NoStripes; 
    // Get Set 
} 

public class Lion : Animal 
{ 
    public bool HasMane; 
    // Get Set 
} 

public class Zoo<T> where T : Animal 
{ 
    public T animal; 
    // Get Set 
} 

Zoo<Tiger> zoo = new Zoo<Tiger>(); 
zoo.animal = new Tiger(); 
zoo.animal.NoStripes = 1; 
0

뭔가를 시도 할 수 너는 zoo.Animal이 사실은이라는 것을 알아야한다.3210. zoo.Animal is Tiger을 사용하여 테스트 할 수 있습니다 (as 연산자와 is의 비교 연산자가 더 좋음).

그러나 일반적으로 프로그램을 이렇게 디자인하면 아주 좋은 냄새가 나지 않습니다. 작성해야 할 코드가 복잡 할 가능성이 큽니다.

+0

이 합의 과정의 점검을 null로 할 수있는 null 참조 예외를 방지하려면 어떻게 그것을 해결하기 위해?/또는,를 포함 할 개체가있는 경우 차고에는 자동차 A 또는 자동차 B가 있으며, 그 다음에 가장 적합한 설계 방법은 무엇입니까? 포함하는 개체 내에 A와 B를 모두 만드는 것은 잘못된 것 같습니다. – DAE

관련 문제