代码之家  ›  专栏  ›  技术社区  ›  Radu

从共享(或静态)函数调用其他函数

  •  1
  • Radu  · 技术社区  · 16 年前

    我得到这个错误: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.

    Partial Class _Default
        Inherits System.Web.UI.Page
    
        <WebMethod()> _
        Public Shared Function ParseData() As String
            Dim value as string = GetValue()
        End Function
    
        Private Function GetValue() as String
            Return "halp"
        End Function
    End Class
    

    我知道这与第一个函数是共享的这一事实有关,第二个函数也应该是公共的,但我不完全理解它背后的原因。可能不相关,但我是从一些JavaScript调用Web方法。

    1 回复  |  直到 16 年前
        1
  •  4
  •   Chase Florell    16 年前
    Partial Class _Default
        Inherits System.Web.UI.Page
    
        <WebMethod()> _
        Public Shared Function ParseData() As String
            Dim value as string = GetValue()
        End Function
    
        Private Shared Function GetValue() as String
            Return "halp"
        End Function
    End Class
    

    Partial Class _Default
        Inherits System.Web.UI.Page
    
        <WebMethod()> _
        Public Function ParseData() As String
            Dim value as string = GetValue()
        End Function
    
        Private Function GetValue() as String
            Return "halp"
        End Function
    End Class
    

    如果必须共享,则使用第一个。如果您可以先初始化对象,或者从同一类中调用它,请使用第二个对象。

    正如您所指出的,webmethod必须是共享的(静态的)。在这种情况下,还必须共享从WebMethod调用的方法。

    编辑 :

    另一种选择是为“getValue”创建单独的类

    Partial Class _Default
        Inherits System.Web.UI.Page
    
        <WebMethod()> _
        Public Shared Function ParseData() As String
            Dim util As Utilities = New Utilities
            Dim value as string = util.GetValue()
        End Function
    End Class
    
    Public Class Utilities  ''# Utilities is completely arbitrary, you can use whatever you like.
        Public Function GetValue() as String
            Return "halp"
        End Function
    End Class
    
    推荐文章