简体   繁体   中英

Use shared/static Property with Activator.CreateInstance

I'm upgrading a .NET 2.0 WinForms application to .NET 4.5.2 and am receiving two warning on this block of code:

Public Sub ShowFormAsMdiChild(ByVal newFormType As Type, _
                              ByVal mdiParentType As Type, _
                              Optional ByVal SearchID As String = "",
                              Optional ByVal curType As SearchType = SearchType.Residential)

    If SearchID = "" Then
        Dim F As Form
        F = CType(Activator.CreateInstance(newFormType), Form)
        F.MdiParent = CType(Activator.CreateInstance(mdiParentType), Form).ActiveForm
        F.Show()
    Else
        Dim F As Form
        Dim args(1) As Object
        args(0) = SearchID
        args(1) = curType

        F = CType(Activator.CreateInstance(newFormType, args), Form)
        F.MdiParent = CType(Activator.CreateInstance(mdiParentType), Form).ActiveForm
        F.Show()
    End If
End Sub

I receive the following warning on the two lines that set F.MdiParent:

Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.

The problem is that the ActiveForm Property is a shared Property and because the code is creating a new instance of the Form, calling the a Form's shared Property causes the warning.

Is there a better way to implement without the warning? Preferred answer in VB.NET, but I can translate if you only know how in C#.

There's no need to create a new instance of the MDI parent type, and then cast it to Form . ActiveForm is a shared property of the Form class, so you should access it through the class name, not through an instance.

F.MdiParent = Form.ActiveForm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM