我想知道为什么Visual Studio会发出此警告:
通过实例访问共享成员,常量成员,枚举成员或嵌套类型
我的代码:
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
什么意味着“通过实例”?另外,为什么这是“警告”?
最佳答案
显示警告是一种设计选择。在C#中,使用实例(this
)关键字调用静态变量时将引发错误。
问题是您应该调用该对象以正确描述它是什么。
有关更多有用的信息,请参见MSDN。
通过实例变量访问Shared成员可能会使您的代码更难理解,因为它会掩盖该成员为Shared的事实。
(...)
更正此错误
使用定义Shared成员的类或结构的名称来访问它,如以下示例所示。
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