首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从静态方法调用和访问非静态方法

从静态方法调用和访问非静态方法
EN

Stack Overflow用户
提问于 2017-09-20 12:00:25
回答 1查看 678关注 0票数 0

要从asp.net c#中的静态方法访问非静态方法。

代码语言:javascript
运行
复制
private void nonstaicMethod(string var1)
{
  //accessing the view/panel from the current page
  //or using 'Response' to download a file
}
[System.Web.Services.WebMethod(EnableSession = true)]
public static void method1(string Id)
{
  CurrentPageName cp=new CurrentPageName();
  cp.nonstaicMethod();
}

对于下载的文件,我得到了response is not available in this context。我试过了,

代码语言:javascript
运行
复制
 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />

 `HttpContext context = HttpContext.Current`;

当我通过网络时,我尝试了很多方法。毫无办法。当我尝试调用非静态并从当前页面访问视图/面板时,我得到了Object reference not set to an instance of an object.

EN

回答 1

Stack Overflow用户

发布于 2017-09-20 12:18:46

将行为放在页面中并试图从其他地方调用它看起来真的是错误的。如果需要,它可能应该放在另一个类中,并将Page实例作为依赖项。在这里,整个模式都在尖叫,有问题,我会避免它,即使在委托的帮助下,possible.However也可以实现同样的事情。

代码语言:javascript
运行
复制
public class MyClass
    {

    private static Action NonStaticDelegate;

    public void NonStaticMethod()
    {
        Console.WriteLine("Non-Static!");
    }

    public static void CaptureDelegate()
    {
        MyClass temp = new MyClass();
        MyClass.NonStaticDelegate = new Action(temp.NonStaticMethod);
    }

    public static void RunNonStaticMethod()
    {
        if (MyClass.NonStaticDelegate != null)
        {
            // This will run the non-static method.
            //  Note that you still needed to create an instance beforehand
            MyClass.NonStaticDelegate();
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46313071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档