Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
asp.net在页面之间传递类的实例_Asp.net_Vb.net - Fatal编程技术网

asp.net在页面之间传递类的实例

asp.net在页面之间传递类的实例,asp.net,vb.net,Asp.net,Vb.net,在第一页上,我想创建一个类的实例: pOne = New pClass() xOne = New xClass(pOne) 然后在接下来的几页中,我希望能够使用pOne和xOne。由于pOne和xOne是第一页的本地对象,如何在其他页中使用它们?您可以使用会话变量存储该对象并在另一页中使用它 //Set the session Session["p1"]=pOne; Session["x1"]=xOne; 在第二页,阅读课时 if(Session["p1"]!=null) {

在第一页上,我想创建一个类的实例:

    pOne = New pClass()
    xOne = New xClass(pOne)

然后在接下来的几页中,我希望能够使用pOne和xOne。由于pOne和xOne是第一页的本地对象,如何在其他页中使用它们?

您可以使用会话变量存储该对象并在另一页中使用它

//Set the session
Session["p1"]=pOne;
Session["x1"]=xOne;
在第二页,阅读课时

if(Session["p1"]!=null)
{
   // If object is present in session, Cast that to our class (PClass) type
   PClass objP1=(PClass) Session["p1"];  
   //Now you can use objP1
}
if(Session["x1"]!=null)
{
   XClass objx1=(XClass) Session["x1"];  
   //Now you can use objx1 
}
在访问变量之前,总是进行空检查是一种很好的做法

这是VB.NET版本(我希望这能起作用,我在VB.NET方面没有太多经验)

在第二页阅读课时

 if Session("p1") IsNot Nothing Then
   Dim objP1 As pClass       
   objP1=CType(Session("p1"),pClass)   
   'Now you can use objP1
 End If

 if Session("x1") IsNot Nothing Then
   Dim objX1 As xClass
   objX1=CType(Session("x1"),xClass)
   'Now you can use objX1
 End If

您可以使用
HttpContext.Items
,这样您就不必清理滞留的对象,除非您重置它们,否则它们将消失:


除非您想使用VB.net而不是Shyju使用的C#the Shyju:PIf,否则如果要这样做,您肯定应该在项目的资源或设置文件中创建条目,并在访问会话时引用这些条目。没有什么比追踪与打字错误相关的错误更令人恼火的了。要小心将对象写入会话。整个对象图必须序列化和反序列化。这可能不是一个主要的开销,取决于您的对象,但我见过有人将大型组合对象写入会话…我一直在会话对象中这样做-但这让我有点担心性能。目前,我的用户基数很小,性能也可以接受,但随着规模的扩大,我不知道在会话对象中存储类实例的扩展性会有多好。在会话中存储很多对象并不好。在这种情况下,我建议您在querystring中传递ID并再次加载对象。
 if Session("p1") IsNot Nothing Then
   Dim objP1 As pClass       
   objP1=CType(Session("p1"),pClass)   
   'Now you can use objP1
 End If

 if Session("x1") IsNot Nothing Then
   Dim objX1 As xClass
   objX1=CType(Session("x1"),xClass)
   'Now you can use objX1
 End If