【问题标题】:Non-static properties in Partial class of System.Web.UI.Page getting reset in functionsSystem.Web.UI.Page 的 Partial 类中的非静态属性在函数中被重置
【发布时间】:2012-09-22 08:31:34
【问题描述】:

部分类 _Default 中的变量在函数调用中被重置,如下面的代码中所述。但是,在将属性标记为静态时,它们的值将被保留。

我的问题是,为什么会发生这种情况?每个函数调用不是使用相同的页面类实例吗?

public partial class _Default : System.Web.UI.Page
{
    public double ValueToConvert { get; set; }
    public double ConvertedValue { get; set; }

    protected void Page_Load(object sender, EventArgs e){}

    protected void btnUC_Click(object sender, EventArgs e)
    {
        //In this method, the non-static properties ValueToConvert and ConvertedValue
        //get reset. But why?
    }

}

【问题讨论】:

标签: c# .net web-applications


【解决方案1】:

不是每个函数调用都使用相同的页面类实例吗?

每个请求都会创建一个新的类实例。哎呀,他们可能在不同的进程甚至不同的机器上。如果您有多个方法调用在同一个请求中 将使用同一个实例,否则您需要计算出您希望如何传播状态。您可以通过客户端(视图状态)传播它或将其存储在服务器端的某个地方(例如,在数据库中)。

【讨论】:

  • 谢谢,乔恩!这就解释了!有没有办法在同一个请求中强制执行多个调用?
  • @TheSilverBullet:您需要更具体地说明“多次调用”的含义。仔细考虑网络的工作方式......
  • 乔恩,我意识到 who 实际上是在回答我的问题,我感到非常谦卑!再次感谢。
【解决方案2】:

您可以通过使用隐藏字段并使用这样的属性包装它们来解决此问题

public partial class _Default : System.Web.UI.Page
{
    public double ValueToConvert \
    { 
       get{
           return hfValueToConvert.Value;  
       }
       set{
           hfValueToConvert.Value = this.value.ToString();
       }
    }

    public double ConvertedValue
    { 
       get{
           return hfConvertedValue.Value;  
       }
       set{
           hfConvertedValue.Value = this.value.ToString();
       }
    }

    protected void Page_Load(object sender, EventArgs e){}

    protected void btnUC_Click(object sender, EventArgs e)
    {
        //In this method, the non-static properties ValueToConvert and ConvertedValue
        //get reset. But why?
    }

}

现在将两个 HiddenField 控件名称 hfValueToConverthfConvertedValue 添加到您的 aspx 页面。

【讨论】:

  • 我已经通过使用静态变量解决了这个问题。我只是想知道为什么普通变量不起作用。
  • @TheSilverBullet:不要为此使用静态变量。这些变量将在 所有 请求之间共享,而与客户端无关。我非常怀疑这就是你想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
  • 1970-01-01
  • 2013-08-17
相关资源
最近更新 更多