我有一个抽象类付款,由多个PaymentTypes实现
public abstract class Payment
{
protected int contract;
public Payment(int contract)
{
this.contract = contract;
}
public abstract bool Aprove();
}
然后,实现它的两个类
public class PaymentA : Payment
{
public PaymentA(int contract) : base(contract)
{
this.contract = contract;
}
public override bool Aprove()
{
return true;
}
}
public class PaymentB : Payment
{
public PaymentB(int contract) : base(contract)
{
this.contract = contract;
}
public override bool Aprove()
{
return true;
}
}
现在,我需要根据表单字段创建PaymentA或PaymentB
static void Main(string[] Args)
{
int contract = 1;
Payment payment;
switch (rbtPaymentType)
{
case (int)EPaymentTypes.A:
payment = new PaymentA(contract);
break;
case (int)EPaymentTypes.B:
payment = new PaymentB(contract);
break;
}
payment.Aprove(); //Use of unassigned local variable
}
我有两个问题:
1 - 它是否构造良好所以我可以致电payment.Aprove()无论是哪种付款方式?
2 - 如果对象未初始化,我该如何进行方法调用?我收到错误“使用未分配的局部变量”
提前致谢
答案 0 :(得分:0)
1 - 它是否构造良好所以我可以致电payment.Aprove()无论是哪种付款方式?
是的,对于简单的应用程序,它没关系。如果你想让它变得更好一点,你可以像这样使用简单的工厂:
public class PaymentFactory
{
public Payment CreatePayment(int rbtPaymentType, int contract)
{
switch (rbtPaymentType)
{
case (int)EPaymentTypes.A:
return new PaymentA(contract);
case (int)EPaymentTypes.B:
return new PaymentB(contract);
default:
throw new Exception("Unknown payment type");
}
}
}
class Program
{
static void Main(string[] Args)
{
int contract = 1;
Payment payment = null;
int rbtPaymentType = 1;
PaymentFactory paymentFactory = new PaymentFactory();
payment = paymentFactory.CreatePayment(rbtPaymentType, contract);
payment.Aprove();
}
}
每当您切换某些内容以创建新实例时,您应该考虑将其封装在工厂中。这样,如果要创建另一个Payment实例,则无需在其他位置重复相同的开关。
2 - 如果对象未初始化,我该如何进行方法调用?我收到错误“使用未分配的局部变量”
您可以将其指定为null,就像我在上面的示例中所示。
顺便说一下。您不必在PaymentA和PaymentB的构造函数中分配合同成员,因为基类会为您完成。