我有一BankAccount
堂课。FixedBankAccount
并SavingsBankAccount
由此衍生。
如果收到的对象不是派生对象,我需要抛出异常。我有以下代码。
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
还有比这更好的代码吗?