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

时间:2010-08-20 04:20:32

标签: asp.net vb.net static shared

我收到此错误: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

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

1 个答案:

答案 0 :(得分:4)

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