加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 从WebMethod访问函数背后的代码

发布时间:2020-12-16 09:16:37 所属栏目:asp.Net 来源:网络整理
导读:我有一个代码隐藏页面,有几种方法;其中一个是页面方法. [WebMethod]public static void ResetDate(DateTime TheNewDate){ LoadCallHistory(TheNewDate.Date);}protected void LoadCallHistory(DateTime TheDate){ bunch of stuff } 当页面加载时,方法LoadCal
我有一个代码隐藏页面,有几种方法;其中一个是页面方法.

[WebMethod]
public static void ResetDate(DateTime TheNewDate)
{
    LoadCallHistory(TheNewDate.Date);
}

protected void LoadCallHistory(DateTime TheDate)
{ bunch of stuff }

当页面加载时,方法LoadCallHistory工作正常,我可以从页面内的其他方法调用它.但是,在Web方法部分中,它以红色加下划线,并显示错误“非静态字段需要对象引用”.

如何从代码的页面方法部分访问函数?

谢谢.

解决方法

如果没有类的实例,则无法从静态上下文中调用非静态方法.从ResetDate中删除静态或使LoadCallHistory静态.

但是,如果从ResetDate中删除静态,则必须具有该实例才能使用该方法.另一种方法是在ResetDate中创建类的实例,并使用该实例调用LoadCallHistory,如下所示:

[WebMethod]
public static void ResetDate(DateTime TheNewDate)
{
    var callHistoryHandler = new Pages_CallHistory();
    callHistoryHandler.LoadCallHistory(TheNewDate.Date);
}

错误消息指示ResetDate具有关键字static而LoadCallHistory不具有.当使用静态时,两个方法都需要是静态的,或者被调用的方法需要是静态的,如果被调用的方法不是静态的,则调用者不能是静态的.

在“Static Classes and Static Class Members”引用MSDN

A static class is basically the same as a non-static class,but there is one difference: a static class cannot be instantiated. In other words,you cannot use the new keyword to create a variable of the class type. Because there is no instance variable,you access the members of a static class by using the class name itself.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读