-->

“Access of shared member, constant member, enum me

2020-08-11 00:40发布

问题:

I wonder why Visual Studio is raising this warning:

Access of shared member, constant member, enum member or nested type through an instance

My code:

Dim a As ApplicationDeployment = deployment.Application.ApplicationDeployment.CurrentDeployment

If System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed Then
    If a.IsNetworkDeployed Then
        ' do something   
    End If
End If

What implies "through an instance"? Also, why is this a "warning"?

回答1:

Showing a warning is a design option. In C#, it would throw an error when calling a static using an instance (this) keyword.

The problem is that you should call the object to correctly describe what it is.

More useful info at MSDN.

Accessing a Shared member through an instance variable can make your code more difficult to understand by obscuring the fact that the member is Shared.

(...)

To correct this error

  • Use the name of the class or structure that defines the Shared member to access it, as shown in the following example.

    Public Class testClass
        Public Shared Sub sayHello()
            MsgBox("Hello")
        End Sub
    End Class
    
    Module testModule
        Public Sub Main()
            ' Access a shared method through an instance variable.
            ' This generates a warning.
            Dim tc As New testClass
            tc.sayHello()
    
            ' Access a shared method by using the class name.
            ' This does not generate a warning.
            testClass.sayHello()
        End Sub
    End Module