2012-07-03 2 views
4

나는 BankAccount 클래스를 가지고 있습니다. FixedBankAccountSavingsBankAccount이 파생됩니다.
수신 된 개체가 파생 개체가 아닌 경우 예외를 throw해야합니다. 다음 코드가 있습니다.기본 클래스 객체 또는 파생 객체인지 확인하는 방법은 무엇입니까?

IEnumerable<DBML_Project.BankAccount> accounts = AccountRepository.GetAllAccountsForUser(userId); 
foreach (DBML_Project.BankAccount acc in accounts) 
{ 
    string typeResult = Convert.ToString(acc.GetType()); 
    string baseValue = Convert.ToString(typeof(DBML_Project.BankAccount)); 

    if (String.Equals(typeResult, baseValue)) 
    { 
     throw new Exception("Not correct derived type"); 
    } 
} 

namespace DBML_Project 
{ 

public partial class BankAccount 
{ 
    // Define the domain behaviors 
    public virtual void Freeze() 
    { 
     // Do nothing 
    } 
} 

public class FixedBankAccount : BankAccount 
{ 
    public override void Freeze() 
    { 
     this.Status = "FrozenFA"; 
    } 
} 

public class SavingsBankAccount : BankAccount 
{ 
    public override void Freeze() 
    { 
     this.Status = "FrozenSB"; 
    } 
} 

} // namespace DBML_Project 

더 좋은 코드가 있습니까?

+0

, 그냥 경우에 확인 변경 그것 (acc.getType() == 대해서 typeof (DBML_Project.BankAccount)) –

+0

그것은 당신이 원하는 무엇인지 분명하지 않다. 컴파일러는 여러분이나 다른 누구도'BankAccount'에서 파생되지 않은'accounts'에 obejct를 추가하지 않으므로 체크 할 필요가 없습니다. –

+0

@AseemGautam :'acc'가 파생 된 타입이면'false'를 반환합니다. –

답변

2

내가 인터페이스를 정의 할 검사 (IAccettableBankAccount 같은 것을,하지만 당신은 도메인을 알고, 그래서 당신은 더 나은 이름을 찾을 수 있어야합니다)와 FixedBankAccount 및 SavingsBankAccount 그것을 구현해야합니다. 그런 다음 테스트는 간단하게 다음과 같습니다

if (!acc is IAccettableBankAccount) 
{ 
    throw new Exception("Not correct derived type"); 
} 
+0

아이디어를 주셔서 감사합니다. 현재 구현 된 것보다 낫습니까? – Lijo

+1

그것은 다릅니다. BankAccount의 모든 하위 클래스 (이후 클래스까지도)는 항상 OK가되며, BankAccount에서 파생 된 클래스를 가질 수도 있지만 예외를 throw 할 수 있습니다. –

5

선언는 BankAccount 클래스를 사용한다. 추상적도 도움이 될 수 있습니다로 클래스를 선언

var accounts = AccountRepository.GetAllAccountsForUser(userId); 
    if (accounts.Any(acc => acc.GetType() == typeof(DBML_Project.BankAccount))) { 
     throw new Exception("Not correct derived type"); 
    } 

,하지만 귀하의 경우 옵션이 있는지 모르겠어 :

+0

이 질문에 어떻게 도움이됩니까? –

+2

메소드의 호출자가 파생 된 유형을 전달하도록 제한 할 것이고 검사를 전혀 필요로하지 않을 것입니다. –

+1

Ooh, 이제 그는 실제로 그가 요구하는 것을 얻었습니다 ... 질문을 읽는 것에서, 그는 형식 호환성을 직접 확인하기를 원하는 것처럼 보였습니다. –

0

당신은 직접 유형을 확인할 수 있습니다.

2

사용 Type.IsSubclassOf 방법. 더 많은 정보 this

foreach (DBML_Project.BankAccount acc in accounts) 
{ 
    if (!acc.GetType().IsSubclassOf(typeof(DBML_Project.BankAccount)) 
    { 
     throw new Exception("Not correct derived type"); 
    } 
} 
관련 문제