【问题标题】:"Access of shared member, constant member, enum member or nested type through an instance"“通过实例访问共享成员、常量成员、枚举成员或嵌套类型”
【发布时间】:2014-04-18 02:47:35
【问题描述】:

我想知道为什么 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

什么意味着“通过实例”?另外,为什么这是“警告”?

【问题讨论】:

  • 您的问题不太清楚 - 您在更新中指的是“第一”和“第二”行吗?
  • 该警告最简单的原因是您正在使用实例变量(在您的示例中为a)来访问共享方法或属性。 VB 允许这样做,但会产生警告。 C# 不允许这样做,这将是 C# 中的错误。
  • 哪一行显示警告,哪一行不显示?从您的更新中不清楚。

标签: .net vb.net warnings shared instance-variables


【解决方案1】:

显示警告是一种设计选项。在 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
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多