我有一个继承自SafeChargeDeposit
的课程BaseExternalDeposit
BaseExternalDeposit
在其构造函数中需要变量类型BaseDepositStructure
。
因为它需要BaseDepositStructure
我无法在SafeChargeDeposit
中使用其子元素。
这是代码:
abstract class BaseExternalDeposit
{
public abstract BaseExternalDepositResult DoDeposit();
protected BaseDepositStructure depositStructure;
public BaseExternalDeposit(BaseDepositStructure depositStructure)
{
this.depositStructure = depositStructure;
}
}
class SafeChargeDeposit : BaseExternalDeposit
{
public SafeChargeDeposit(CreditCardDepositStructure depositStructure):base(depositStructure){}
public override BaseExternalDepositResult DoDeposit(){
/////// I CAN USE THIS MEMBER:
depositStructure.Amount = 50;
/////// BUT I CANNOT USE THIS MEMBER:
depositStructure.CreditCardNumber = "123456";
}
}
public class BaseDepositStructure
{
public double Amount = 0.0;
}
public class CreditCardDepositStructure : BaseDepositStructure
{
public string CreditCardNumber = string.Empty;
}
我理解为什么我可以使用depositStructure.Amount并且不能使用depositStructure.CreditCardNumber ... 但是我的设计出了什么问题呢?如何解决这个问题并保持使用Bases的灵活性。
答案 0 :(得分:4)
interface IBaseExternalDepositResult
{
}; // eo interface BaseExternalDepositResult
interface IDeposit
{
void Deposit();
};
// class BaseExternalDeposit<>
abstract class BaseExternalDeposit<B> : IDeposit where B : BaseDepositStructure
{
private B depositStructure_;
protected abstract IBaseExternalDepositResult DepositImpl();
protected B Structure { get { return depositStructure_; } }
public BaseExternalDeposit(B depositStructure)
{
depositStructure_ = depositStructure;
} // eo ctor
// IDeposit
void Deposit()
{
DepositImpl();
}
} // eo class BaseExternalDeposit<B>
// class SafeChargeDeposit
class SafeChargeDeposit : BaseExternalDeposit<CreditCardDepositStructure>
{
protected override IBaseExternalDepositResult DepositImpl()
{
Structure.Amount = 50;
Structure.CreditCardNumber = "123456";
} // eo DepositImpl
public SafeChargeDeposit(CreditCardDepositStructure depositStructure)
: base(depositStructure)
{
}
} // eo class SafeChargeDeposit
public class BaseDepositStructure
{
public double Amount = 0.0;
}
public class CreditCardDepositStructure : BaseDepositStructure
{
public string CreditCardNumber = string.E