나는 BankAccount
클래스를 가지고 있습니다. FixedBankAccount
및 SavingsBankAccount
이 파생됩니다.
수신 된 개체가 파생 개체가 아닌 경우 예외를 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
더 좋은 코드가 있습니까?
, 그냥 경우에 확인 변경 그것 (acc.getType() == 대해서 typeof (DBML_Project.BankAccount)) –
그것은 당신이 원하는 무엇인지 분명하지 않다. 컴파일러는 여러분이나 다른 누구도'BankAccount'에서 파생되지 않은'accounts'에 obejct를 추가하지 않으므로 체크 할 필요가 없습니다. –
@AseemGautam :'acc'가 파생 된 타입이면'false'를 반환합니다. –