构造函数多态性帮助

时间:2009-09-04 02:27:10

标签: asp.net constructor polymorphism

我有一个UserControl,它有一个BaseClass对象作为公共成员。现在我正在做以下事情以辨别我需要实例化哪种类型的对象:

Public WithEvents theForm As OrderForm

Protected Sub Page_Load(ByVal sender As Object, _
   ByVal e As System.EventArgs) Handles Me.Load

    Select Case Form
        Case OrderItem.ItemsFor.Invoice
            theForm = New Invoice(FormID)
        Case OrderItem.ItemsFor.PurchaseOrder
            theForm = New PurchaseOrder(FormID)
    End Select

End Sub

InvoicePurchaseOrder都继承OrderForm作为基类,FormID是整数。我知道这是错的,但我想知道正确的方法。

1 个答案:

答案 0 :(得分:2)

通常我会从后面的代码中删除逻辑并创建一个简单的抽象工厂。抽象工厂的目的是创建相同基类型的对象,但可以辨别从鉴别器创建的类型。 C#中的一个简单示例如下所述:

public class OrderFormFactory
{
   public static IOrderForm Create(string orderType, int formId)
   {
       IOrderType orderTypeToCreate = null;
       switch(orderType)
       {
          case OrderType.Invoice:
              orderTypeToCreate = new Invoice(formId);
              break;
          case OrderType.PurchaseOrder:
              orderTypeToCreate = new PurchaseOrder(formId);
              break;
          default:
              throw new ArgumentException("Order Type of " + orderType + " is not supported";
       }
       return orderTypeToCreate;
   }
}