gpt4 book ai didi

c# 设计模式 - 与 Base 交互

转载 作者:行者123 更新时间:2023-11-30 21:11:43 26 4
gpt4 key购买 nike

我有一个类 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 的灵 active 。

最佳答案

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

关于c# 设计模式 - 与 Base 交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7888350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com