如何在asp.net中重置静态变量 [英] how to reset static variable in asp.net

查看:125
本文介绍了如何在asp.net中重置静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。我要开发像网上购物这样的网络应用程序,这意味着这样的概念。我的数据库中有很多图像可以成功从数据库中检索。如果需要进一步选择我将所有这些图像放在asp中:超链接

喜欢

 <   asp:HyperLink     id   =   hyperlink1  

ImageUrl =' < % #Eval( FilePAth %> '

NavigateUrl =' < % string .Format( 〜 /ItemSelection.aspx?&FileName={0}&FilePath={1}\",Eval( fileName),Eval( FilePath))%> '

< span class =code-attribute> 文本 = Microsoft官方网站 目标 = _new < span class =code-attribute> runat = server / >



在ItemSelection.aspx的page_load方法中,我将为所选项目创建动态div和图像控件。对于所选项目,我使用静态List< string> (在App_code / Class.cs中);

将此列表添加到会话varilable。之后将此会话变量添加到动态创建的DIV上的图像控件。



它第一次工作正常。但之后它无法重置静态变量,之前的值显示为它。



Plz帮我重置静态变量。

谢谢。



编辑:AL)更新自评论



谢谢。 ItemSelection.aspx.cs page_load事件中的代码为



 受保护  void  Page_Load( object  sender,EventArgs e)
{
Class1 c = < span class =code-keyword> new Class1();

if (Request.QueryString [ FilePath]!= null
{
Session [ itemcount] = Convert.ToInt32(会话[ itemcount])+ 1 ;
int count = Convert.ToInt32(会话[ ITEMCOUNT]的ToString());
// 此处label2用于选择的项目
label2。 Text = count.ToString();
// list2用于商店选择项目
列表list2 = new List();

// Response.Write(count =+ count);
// 这里我们在list2中添加所选项目

list2 .Add(Request.QueryString [ FilePath]);

// 然后我将此列表添加到app_code / class <下的类中创建的静态列表中/ span>

c.setArr(list2);
会话[ itemList] = c.getArr();

// 如果选择了项目,那么我只创建了带图像控制的动态div
if (count > 0
{
for int i = 0 ; i < count; i ++)
{
HtmlGenericControl div1 = new HtmlGenericControl( div);

string j =(i + 1 )。ToString();
div1.Attributes.Add( id j);
// Response.Write(div1.Attributes.ToString());
div1.Attributes.Add( class top_rounded);
Image img = new Image();

// 列出a = c.listItem;
列表a =(列表)会话[ itemList]; img.ImageUrl = a [i];
div1.Controls.Add(img);
Panel1.Controls.Add(div1);
}
}

解决方案

确定 - 您不希望该列表是静态的。只需关闭静态键工作。



Class1 c(aweful class name,btw)将保留其整个生命周期的非静态值。它的生命取决于它的范围。考虑这些范围和示例。



如果在if,for循环中使用等声明一个实例,那么它的范围就是那个部分。一旦该部分关闭,它就不再可用。它已经死了。

  int  x; 
for int y = 0 ; y < 10 ; y ++){x = y;}
int a = x; // 罚款;
a = y; // 编译错误。 y不再存在





如果在方法中声明一个实例,那么当该方法退出时,它的生命就会结束。这是您正在使用的范围。似乎该方法中的其他地方没有使用该列表,因此这是适当的范围。

  int  x; 
void method(){
int y = 10 ;
x = y;
}
void Main(){
method();
int a = x; // fine
a = y; // 编译错误。 y不再存在
}





如果在类中声明一个实例,那么它会在班级死了。在类本身离开范围之后会发生这种情况。

  class  MyClass { public   int  y { get ;  set }} 
void method(){
int x = 10 ;
使用(myClass = new MyClass())
{
myClass.y = x;
int a = myClass.y;
}
int b = x; // fine
b = myClass.y / / 好吧,myClass不再存在,所以myClass.y也不存在。
}





如果将实例声明为静态,那么在整个应用程序终止之前它不会消亡。它的范围是最大的。



  class  MyClass { public   static   int  y =  10 < /跨度>; } 
void method(){
int x = MyClass.y; // fine
// 我们甚至不需要MyClass的实例来查找y。无论实例化多少个MyClass对象,它总会存在并且总有一个实例。
}







看看这4个级别的范围。想想你的实例是如何被使用的。它真的需要是静态的吗?它可以代替方法或类范围吗?你是否需要Class1,或者你只是在其中一个范围内使用List变量?


我不确定你在做什么,但你使用静态变量可能不正确。静态变量是所有用户的全局,它们在首次使用时初始化并存在,直到重新启动站点。你需要仔细考虑是否真的需要使用静态变量,如果你需要,你需要记住它们的全局性,考虑线程安全问题等等。


该解决方案满足了OP的要求,这与要求的问题不同。我这样做是希望有相同问题的人会找到它。





还有另一种类型的范围不是上面提到的。这是会话范围,特定于Web应用程序。



网站上的任何用户都将获得会话ID。这通常以客户端计算机上的cookie形式保存。该会话ID涉及可以在服务器端用于标识用户的会话对象。一旦用户存在该网站,该会话就会到期。如果同一用户回来,那么他们将获得与新会话相关的新会话ID。



注意:如果用户在多个浏览器中打开网站(即Chrome和IE)或以正常和隐身模式打开,然后每个都会有单独的会话。



那么:如何使用它们?简单易行:

在您的代码隐藏中,您可以通过名为简单会话的SessionState对象访问用户会话。您不必担心将其连接到用户会话。这一切都为你完成了。观察:

  public   void  Page_Load( blah){
if (会话[ 购物篮] == null
会话[ Basket] = new List< items>();
}
public void addToBasket(item){
// 存储为对象,因此您必须转换为变量
List< items> basket =(List< items>)会话[ Basket];
basket.Add(item);
会话[ Basket] = basket;
}
< / items > < / 项目 > ; < / items >







当用户离开网站时,会话及其会话的所有值死了。



怎么样? ^ _ ^


Hi,everyone.I am going to develop web application like online shopping that means concept like that.I have lots of images in my datalist which are retrieve from database successfully.Now for further selection i put all these images in asp:hyperlink
like

<asp:HyperLink id="hyperlink1"

                 ImageUrl='<%#Eval("FilePAth") %>'

                 NavigateUrl='<%# string.Format("~/ItemSelection.aspx?&FileName={0}&FilePath={1}",Eval("fileName"),Eval("FilePath")) %>'

                 Text="Microsoft Official Site" Target="_new"   runat="server"/>


In the page_load method of ItemSelection.aspx I am going to create dynamic div and image control for selected item.For selected item i used static List<string> (in App_code/Class.cs);
add this list to session varilable.After that add this session variable to image control on dynamically created DIV.

It working fine for 1st time.but after that it can't reset static variables,previous values show as it.

Plz help me to reset the static variable.
thanks.

EDIT: AL) Updated from Comments

thanks. The code in ItemSelection.aspx.cs page_load event as

protected void Page_Load(object sender, EventArgs e)
{ 
  Class1 c = new Class1();

  if (Request.QueryString["FilePath"] != null)
  {
    Session["itemcount"] = Convert.ToInt32(Session["itemcount"]) + 1;
    int count = Convert.ToInt32(Session["itemcount"].ToString());
    //here label2 is used for no.of item selected
    label2.Text = count.ToString();
    //list2 is used for store selected item 
    List list2 = new List();

    //Response.Write("count=" + count);
    //Here we add selected item in list2 

    list2.Add(Request.QueryString["FilePath"]);

    // then i added this list into static list created in class under app_code/class

    c.setArr(list2);
    Session["itemList"]= c.getArr();

    //If item selected then only i have created dynamic div with image control 
    if (count > 0)
    {
      for (int i = 0; i < count; i++)
      {
        HtmlGenericControl div1 = new HtmlGenericControl("div");

        string j = (i + 1).ToString();
        div1.Attributes.Add("id", "j");
        //Response.Write(div1.Attributes.ToString());
        div1.Attributes.Add("class", "top_rounded");
        Image img = new Image();

        //List a = c.listItem;
        List a = (List)Session["itemList"]; img.ImageUrl = a[i];
        div1.Controls.Add(img);
        Panel1.Controls.Add(div1);
     }
  }

解决方案

Ok - You do not want that list to be static. Just take the static keywork off.

Class1 c (aweful class name, btw) will retain its non-static values for its whole life. Its life is dictated by its scope. Consider these level of scope and the examples.

If you declare an instance within an if, for loop, using etc. then it's scope is that section. As soon as the section is closed then it is no longer available. It's dead.

int x;
for(int y = 0; y < 10; y++){x=y;}
int a = x; //fine;
a = y; //compile error.  y doesn't exist anymore



If you declare an instance within a method, then it's life ends when that method exits. This is the scope you are using. It appears that the list is not being used anywhere else other that in the method so this is the appropriate scope.

int x;
void method(){
    int y = 10;
    x = y;
}
void Main(){
    method();
    int a = x; //fine
    a = y;  //compile error.  y doesn't exist anymore
}



If you declare an instance in the class then it dies when the class dies. This happens after the class itself has left scope.

class MyClass{ public int y {get;set} }
void method(){
  int x = 10;
  using(myClass = new MyClass())
  {
     myClass.y = x;
     int a = myClass.y;
  }
  int b = x;  //fine
  b = myClass.y //Well, myClass doesn't exist anymore so myClass.y doesn't either.
}



If you declare an instance as static then it will not die until the entire application dies. It's scope is maximal.

class MyClass{ public static int y = 10; }
void method(){
  int x = MyClass.y; // fine
  //We don't even need an instance of MyClass to find y.  It will always be there and there is always 1 instance of it no matter how many MyClass objects are instantiated.
}




Take a look at these 4 levels of scope. Think about how your instance is being used. Does it really need to be static? Can it instead be in the method or class scope? Do you need Class1 at all, or could you just use a List variable in one of these scopes instead?


I'm not really sure what you're doing, but your use of static variables is probably incorrect. Static variables are "global" across all users and they are initialised on first use and exist until the site is restarted. You need to think carefully about if you really need to use static variables or not, and if you do you need to keep in mind their global nature, think about thread safety issues etc etc.


This solution answers the OPs requirements, which differ from the question asked. I do this in the hope that someone who has the same issue will find it.


There is another type of scope that was not mentioned in the above. This is session scope and is specific to web applications.

Any user on the website will be given a session id. This is usually kept in the form of a cookie on the clients machine. This session ID relates to a session object that can be used at the server side to identify the user. Once the user exist the website, this session expires. If the same user comes back then they will get a new session Id relating to a new session.

NB: if a user has the website open in several browsers (i.e. Chrome and IE) or has it open in normal and incognito mode, then each of these will have individual sessions.

So: How to use them? Dead easy:
In your code-behind you can access the users session via the SessionState object called simple "Session". You don't have to worry about wiring it up to the users session. That all gets done for you. Observe:

public void Page_Load(blah){
  if(Session["Basket"]==null)
    Session["Basket"] = new List<items>();
}
public void addToBasket(item){
    //Stored as object so you have to cast to a variable
    List<items> basket = (List<items>)Session["Basket"];
    basket.Add(item);
    Session["Basket"] = basket;
}
</items></items></items>




When the user leaves the website then Session and all of it's values for that session die.

How's that? ^_^


这篇关于如何在asp.net中重置静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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