【问题标题】:Calling other functions from a shared (or static) function从共享(或静态)函数调用其他函数
【发布时间】:2010-08-20 04:20:31
【问题描述】:

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

【问题讨论】:

    标签: asp.net vb.net static shared


    【解决方案1】:
    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
    

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

    正如您所指出的,Web 方法必须是共享的(静态的)。在这种情况下,您从 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
    

    【讨论】:

    • 从我读过的内容来看,WebMethods 必须被共享。这是我唯一的选择吗?
    • 我已经编辑过了。基本上,是的,这是您唯一的选择。错误非常明显。由于“共享”方法的本质,从共享方法调用的方法也必须是共享的。
    • 我进行了另一次编辑。在我的编辑中,您会注意到我创建了一个 Utilities 类的实例,以便我可以调用公共(但不是共享)GetValues 方法。
    • 谢谢,解决了这个错误。是否可以命名它,以便我不必为每次调用重复 util?
    • 对不起,我没有听懂你的最后一个问题。 “命名它,这样我就不必为每个调用重复 util”。您不能初始化命名空间,只能初始化一个类。这就是为什么你使用util.GetValue
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 2011-10-04
    • 1970-01-01
    相关资源
    最近更新 更多