파생 클래스를 기본 클래스를 반환하는 함수의 출력에 할당하는 동안 오류가 발생했습니다.

푸루 사르 타

나는 어딘가에서 읽었습니다.

파생 클래스 (또는 하위 클래스)는 기본 클래스의 인스턴스입니다.

이를 감안할 때 기본 클래스를 상속하는 다음과 같은 문제가 있습니다.

public class TransactionCategorisationRuleViewModel : CategorisationRuleViewModel
{
    public long TransactionId { get; set; }

    [Display(Name="Apply to All Transactions")]
    public bool IsApplyAll { get; set; }

}

또한 다음과 같은 정의를 가진 기능이 있습니다.

public CategorisationRuleViewModel GetNewRule()
{
     // content
}

그러나 이렇게하면 오류가 발생합니다 (암시 적으로 유형 CategorisationRuleViewModel을 TransactionCategorisationRuleViewModel로 변환 할 수 없습니다.)

TransactionCategorisationRuleViewModel vmRule = GetNewRule();
gunr2171

더 쉬운 예를 들어 보겠습니다. 두 가지 클래스가 있습니다.

class Animal { }

class Horse : Animal { }

그리고이 메서드를 호출하려고합니다.

public Animal GetNewAnimal()
{
    // content
}

따라서 다음과 같이 작성하면 :

Horse newHorse = GetNewAnimal();

캐스팅 예외를 제공합니다. GetNewAnimal동물을 반환 하기 때문 입니다. 말일 수도 있고 돼지 일 수도 있습니다. 컴파일러가 확신 할 수없고 암시 적 캐스팅을 수행하고 있기 때문에 "말을 원한다는 것을 알고 있지만 그럴 것이라고 보장 할 수 없으므로 포기합니다."라고 말합니다.

이 문제를 해결하는 방법은 명시 적 캐스팅 을 수행하는 것 입니다.

Horse newHorse = (Horse)GetNewAnimal();

이것은 컴파일러에게 반환 유형이 Horse라는 것을 알려줍니다. 그러나 런타임에 반환 값을 Horse로 캐스팅 할 수없는 경우 시스템은 InvalidCastException.


따라서 예제에 매핑하려면 내 게시물의 모든 말과 동물을 각각 TransactionCategorisationRuleViewModel, 및으로 대체하십시오 CategorisationRuleViewModel.

TransactionCategorisationRuleViewModel vmRule = 
    (TransactionCategorisationRuleViewModel)GetNewRule();

이렇게하면 예외가 해결되지만 GetNewRule실제로 TransactionCategorisationRuleViewModel. TransactionCategorisationRuleViewModel기본 클래스 유형 대신 a를 반환하는 것이 더 쉬울 수 있습니다 .

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관