1

我已经编写了一个基类,我希望从中派生几个子类(在本例中为 Windows 窗体类),并且我使用工厂模式来维护子实例的集合,因此表单只能具有每个主键值一个实例(类似于工厂模式和单例模式的混搭。)

我在基本表单类中使用以下代码:

Public Class PKSingletonForm
   Inherits Form

   Protected _PKValue As Int32 = 0
   Protected _strFormKey As String = ""
   Protected Shared _dictForms As New Dictionary(Of String, PKSingletonForm)

   Public Shared Function GetForm(Of T As {PKSingletonForm, New})(Optional ByVal PKValue As Int32 = 0) As T
      '** Create the key string based on form type and PK.
      Dim strFormKey As String = GetType(T).Name & "::" & PKValue.ToString

      '** If a valid instance of the form with that key doesn't exist in the collection, then create it.
      If (Not _dictForms.ContainsKey(strFormKey)) OrElse (_dictForms(strFormKey) Is Nothing) OrElse (_dictForms(strFormKey).IsDisposed) Then
         _dictForms(strFormKey) = New T()
         _dictForms(strFormKey)._PKValue = PKValue
         _dictForms(strFormKey)._strFormKey = strFormKey
      End If

      Return DirectCast(_dictForms(strFormKey), T)
   End Function
End Class

这个想法是创建一个从基本表单继承的子表单(例如,称为 UserInfoForm),并为用户 #42 创建一个实例,如下所示:

Dim formCurrentUser = PKSingletonForm.GetForm(of UserInfoForm)(42)

所有这些都按预期工作。

但是,UserInfoForm 现在有一些我希望设置的属性,我想使用 Object Initializers 设置它们,而不是在工厂创建表单之后,如下所示:

Dim formCurrentUser As New UserInfoForm With { .ShowDeleteButton = False, .ShowRoleTabs = False }

有没有办法结合这两种方法,所以我有工厂和初始化程序?

我不是在寻找:

Dim formCurrentUser = PKSingletonForm.GetForm(of UserInfoForm)(42)
formCurrentUser.ShowDeleteButton = False
formCurrentUser.ShowRoleTabs = False

...因为基类还有一个 ShowForm() 方法,该方法采用额外的基本表单参数,包装 GetForm() 函数并显示表单。

4

2 回答 2

1

要获得真正的对象初始化器,根据定义,您必须使用New... With

而且因为您有时不想创建新对象,所以这不是一个选择

根据您的其他要求,您的解决方案可能是每次更改为使用新对象,但将单例封装在内部,或者使用类似于:

Dim formCurrentUser As UserInfoForm 
With PKSingletonForm.GetForm(of UserInfoForm)(42)
  .ShowDeleteButton = False
  .ShowRoleTabs = False
  formCurrentUser = .Self
End With

Dim formCurrentUser = PKSingletonForm.GetForm(of UserInfoForm)(42) : With formCurrentUser如果不需要上述构造中可用的额外功能(即GetForm可以返回可能具有更多或更少可用属性和方法的另一种类型),则可以简化为。

于 2012-04-01T04:02:27.460 回答
0

我们的 ShowForm() 方法编写如下:

Public Shared Sub ShowForm(Of T As {BaseForm, New})(Optional ByVal PKValue As Int32 = 0, <Several Parameters Here>)

   Dim formShown As BaseForm = GetForm(Of T)(PKValue, isRepeatable)

   <Do Stuff with Parameters Here>

   formShown.Show()
   formShown.BringToFront()
End Sub

我们的解决方案是去掉 Shared(和泛型),将 ShowForm() 简化为:

Public Sub ShowForm(<Several Parameters Here>)

   <Do Stuff with Parameters Here>

   Me.Show()
   Me.BringToFront()
End Sub

这样,我们可以写:

Dim formCurrentUser = PKSingletonForm.GetForm(of UserInfoForm)(42)
formCurrentUser.ShowDeleteButton = False
formCurrentUser.ShowRoleTabs = False
formCurrentUser.ShowForm(blah, blah)

...也:

Dim formCurrentUser = PKSingletonForm.GetForm(of UserInfoForm)(42).ShowForm()
于 2012-04-01T04:08:09.860 回答