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

会有一股神秘感。 提交于 2020-01-13 07:55:52

问题


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
    


来源:https://stackoverflow.com/questions/22377421/access-of-shared-member-constant-member-enum-member-or-nested-type-through-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!