如何在Interface类中设置正确的方法参数

时间:2012-11-03 13:46:03

标签: c# oop interface

每个继承类的方法都需要不同类型的参数。 在这种情况下,我应该如何在Interface Method中定义参数才能使所有子方法都能接受?

public interface IPayment 
{
  void MakePayment(OrderInfo orderInfo); // !!
  void MakeRefund (OrderInfo orderInfo); // !!
}

public class OrderInfo 
{
  protected string OrderNo {get; set;}
  protected string CustomerNo { get; set;}
  protected decimal Amount {get; set;}
}

public class CreditCardPaymentInfo : OrderInfo
{
  string CCNum {get; set;}
  string ExpDate { get; set;}
}

public class GooglePaymentInfo : OrderInfo
{
  string GoogleOrderID {get; set;}
}

public class PaypalPaymentInfo : OrderInfo
{
  string PaypalID {get; set;}
}



public void MakePayment()
{
    IPayment paymentModule;
    // Get Order Info 
    if(orderType == "Paypal"){
        paymentModule = new PaypalPayment();

        PaypalPaymentInfo orderInfo = new PaypalPaymentInfo();
        orderInfo.PaypalID = "TEST";
    }else if(orderType == "Google"){
        paymentModule = new GooglePayment();

        GooglePaymentInfo orderInfo = new GooglePaymentInfo();
        orderInfo.GoogleOrderID = "TEST";
    }else{
        paymentModule = new CreditCardPayment();

        CreditCardPaymentInfo orderInfo = new CreditCardPaymentInfo();
        orderInfo.CCNum = "1111111111111111";
        orderInfo.ExpDate = "11/11";
    }

    orderInfo.OrderNo = "123";
    orderInfo.CustomerNo = "ABC";
    orderInfo.Amount = 12.20m;

    paymentModule.MakePayment();
}

发生错误:

  

错误1'com.WebUI.Models.CreditCardPaymentInfo'未实现接口成员'com.WebUI.Models.IPaymentProcess.makeRefund(WebUI.Models.RefundModel)'

[编辑]

哦,我忘记了我的模型代码,就像这样,

public class CreditCardPayment: IPayment 
{
  public void MakePayment(CreditCardPaymentInfo creditCardPaymentInfo ){...}
  //The parameter type is NOT OrderInfo 
  //public void MakePayment(OrderInfo orderInfo){...}
  public void MakeRefund(CreditCardPaymentInfo creditCardPaymentInfo ){...}
}

但在CreditCardPayment案例中,我需要传递仅包含公共字段的 CreditCardPaymentInfo参数而不是OrderInfo

1 个答案:

答案 0 :(得分:5)

public interface IPayment<T> 
    where T: OrderInfo
{
  void MakePayment( T orderInfo );
  void MakeRefund ( T orderInfo );
}

然后:

public class CreditCardPayment
    : IPayment<CreditCardPaymentInfo>
{
    public void MakePayment( CreditCardPaymentInfo creditCardPaymentInfo ) {
        // ...
    }

    public void MakeRefund( CreditCardPaymentInfo creditCardPaymentInfo ) {
        // ...
    }
}

public class CreditCardPaymentInfo
    : OrderInfo
{
    public string CCNum { get; set; }
    public string ExpDate { get; set; }
}