Cause this VB6-like smell, which VB.NET allows, to error instead: WinFormType.InstanceProp=Value [DISABLE My.Forms]

后端 未结 2 1112
夕颜
夕颜 2020-11-30 15:20

I have notice something very obnoxious with VB.Net\'s treatment of Winform objects.

This has trashed several hours of our time. It will only get worse as we have more

相关标签:
2条回答
  • 2020-11-30 15:44

    No. This confusing behaviour is by design.

    It has been possible in VB to use one instance of a form without creating it, and this behaviour happily made it to VB.NET. To me, this is one of the worst design choices.
    But it does make converting legacy projects easier. And it does a favour to those who never even knew a form could be explicitly instantiated.

    But you are not required to use this trick, as you never were in VB6. In both languages you can use explicitly created instances, in which case the default instance will not be created. Just forget this "feature" exists and only let it back to your mind when enlightening others.

    0 讨论(0)
  • 2020-11-30 16:00

    Sorta. You could create a function or override ShowDialog that checks the My.Forms collection to see if the current instance is in it and if it is thrown an exception. There's not a setting that can be used to prevent it from being used.

    EDIT: adding sample code illustrating the concept (using a beep instead of an exception).

        Shared Function FormIsInMyForms(formName As String, frm As Form)
            If formName = "Form1" Then
                If frm.Equals(Form1) Then
                    Return True
                Else
                    Return False
                End If
            End If
            Return False
    
        End Function
    
        Public Overloads Sub ShowDialog()
    
            If FormIsInMyForms("Form1", Me) Then
                Beep()
            End If
    
            MyBase.ShowDialog()
        End Sub
    

    Doing the same thing via reflection is left as an exercise for the reader... :)

    0 讨论(0)
提交回复
热议问题