在静态Web方法中调用非静态方法 [英] Call a nonstatic method in static web method

查看:86
本文介绍了在静态Web方法中调用非静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非静态方法,我想在静态web方法中调用它.
我已经在静态方法中创建了该类的对象,以调用该非静态方法.

I have a non-static method and i want to call it in a static webmethod.
I have created an object of that class in static method to call that non-static method.

MyClass obj=new MyClass();
obj.nonStatic();



但是它显示出一个例外,即对象引用未设置为对象实例.
您能帮我在静态web方法中调用非静态方法吗?



But its showing exception that object reference not set to instance of object.
Can you help me to call the non-static method in static webmethod.

推荐答案

听起来像您正在使用PageMethod来获取数据并在该方法中尝试上述操作.

您需要知道,页面方法无法与Page类的实例属性和方法进行交互,因为页面方法调用不会创建Page实例或其任何控件.因此,您将无法访问它并收到错误消息.
看看这里,读一读:为什么要使用ASP.NET AJAX页面方法必须是静态的? [
Sounds like you are using PageMethod to get your data and trying the above thing in that method.

You need to know that, Page Methods cannot interact with the instance properties and methods of your Page class, because a page method call creates no instance of the Page or any of its controls. Hence you are unable to access it and get an error.
Have a look here, a good read: Why do ASP.NET AJAX page methods have to be static?[^]


Still, if you really want it then there is a round about way to accomplish it like the following:
// Can call a non-static method through an object reference from within a static method.
public static void staticMeth(MyClass obj) 
{
   // This will not throw an error
   obj.nonStatic(); 
}


这篇关于在静态Web方法中调用非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆