我最近对界面很感兴趣,并且能够进一步定制它们,而不是在默认状态下使用它们。
我一直在研究IList(T)。使用通用列表而不是ArrayLists的优点令我震惊。这是test的图片。这是进一步解释about the Test的网站。
所以,我当然想尝试一下。当我第一次使用ForNext方法遍历列表时,代码工作正常。第二次我无法访问列表中的表单名称,因为它已被处理。任何人都有任何见解如何访问列表中的表单属性。
Public Class frmMain
Dim Cabinet As List(Of Form) = New List(Of Form)
Dim FormA As New Form1
Dim FormB As New Form2
Dim FormC As New Form3
Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles _Me.Load
Cabinet.Add(FormA)
Cabinet.Add(FormB)
Cabinet.Add(FormC)
End Sub
Sub displayForm(ByVal aForm As Form)
Dim myFormName As String = ""
Stopwatch.Start()
If aForm.IsDisposed = False Then
aForm.Show()
Else
myFormName = aForm.(How do I access this objects Name?)
aForm = New Form '<----- I would rather simply use aForm = New(aForm)
aForm.Name = myFormName
aForm.Show()
End If
Stopwatch.Stop()
Dim RealResult As Decimal = (Stopwatch.ElapsedMilliseconds / 1000)
Debug.WriteLine(RealResult)
Stopwatch.Reset()
End Sub
Private Sub btnForEach_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnForEach.Click
'Dim instance as List
'Dim action as Action(of T)
'instance.ForEach(action)
'action = delegate to a method that performs an action on the object passeed to it
Cabinet.ForEach(AddressOf displayForm)
End Sub
我真的不明白为什么如果VB知道这是一个通用列表,这意味着它可以知道列表的类型,并且对象都被约束为表单;为什么我不能在列表中的项目上调用构造函数。防爆。 aForm = New aForm或aForm = New Cabinet.aForm
为我开一个这个人。感谢。
答案 0 :(得分:2)
您无法构造“aForm”的新实例,因为它不是类型,它是Form类型的实例。
如果要阻止ObjectDisposedException,可以隐藏表单而不是关闭它。将以下代码放在后面的每个表单代码中:
Public Class Form1
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Dim form = CType(sender, Form)
form.Visible = False
e.Cancel = True
End Sub
End Class
然而,这有点令人讨厌,但是你不需要Else
块中的代码。
修改强> 你可以试试这个:
Private Sub displayForm(ByVal aForm As Form)
Dim indexOfCab As Integer = Cabinet.IndexOf(aForm)
If indexOfCab <> -1 Then
If aForm.IsDisposed Then
aForm = CreateForm(aForm.GetType())
Cabinet(indexOfCab) = aForm
End If
aForm.Show()
End If
End Sub
Private Shared Function CreateForm(formType As Type) As Form
Return CType(Activator.CreateInstance(formType), Form)
End Function
您不需要那么大的Select
声明。
答案 1 :(得分:0)
这是我能够让它发挥作用的唯一方法。我觉得它效率极低,希望有人能让我走上更好的方法来做到这一点。以下是我想要实现的目标。
子displayForm(ByVal aForm As Form)
Dim myFormName As String = ""
If Cabinet.Contains(aForm) Then
Dim indexOfCab As Integer = Cabinet.IndexOf(aForm)
Dim ObjForm As Form = Cabinet.Item(indexOfCab)
If aForm.IsDisposed Then
Select Case indexOfCab
Case 0
aForm = Nothing
aForm = New Form1
Cabinet.Item(indexOfCab) = aForm
Cabinet.Item(indexOfCab).Show()
Case 1
aForm = Nothing
aForm = New Form2
Cabinet.Item(indexOfCab) = aForm
aForm.Show()
Case 2
aForm = Nothing
aForm = New Form3
Cabinet.Item(indexOfCab) = aForm
Cabinet.Item(indexOfCab).Show()
End Select
Else
Cabinet.Item(indexOfCab).Show()
End If
End If
结束次