我尝试创建一个新的Customer对象并从中检索Cid值,如下所示:
Line 32: Customer temp = new Customer();
Line 33: temp =(Customer)Session["customer"];
Line 34: int id = temp.Cid;
但是我收到了这个错误:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object."
我也试图这样做:
int id = Convert.Toint(temp.Cid);
但它给了我同样的错误
答案 0 :(得分:1)
这意味着Session["customer"]
为null
。您需要先检查Session["customer"]
是否为null
:
if(Session["customer"] != null){
Customer temp =(Customer)Session["customer"];
int id = temp.Cid;
}
如果Session["customer"]
为null
,那么您需要检查以确保正确设置Session["customer"]
。
如果你谷歌object reference not set to an instance of an object stack overflow
,你会注意到这个错误被问了很多。 object reference not set to an instance of an object
,正是它所说的。 Session["customer"]
是一个会话变量,可以保存对象的引用。如果您尚未设置该引用,则Session["customer"]
为空。
答案 1 :(得分:0)
我会首先分配值,然后检查值是否为null。
Customer temp = Session["customer"] as Customer;
if (temp != null) {
int id = temp.Cid;
}
答案 2 :(得分:0)
它会抛出错误,因为Session["customer"]
为空。在转发给客户之前,您需要确保Session["customer"]
不为空。
请参阅以下示例中的 SessionCustomer -
<asp:Label runat="server" ID="Label1" />
<asp:Button ID="PostBackButton" OnClick="PostBackButton_Click"
runat="server" Text="Post Back" />
public class Customer
{
public int Id { get; set; }
}
public Customer SessionCustomer
{
get
{
var customer = Session["Customer"] as Customer;
return customer ?? new Customer();
}
set { Session["Customer"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SessionCustomer = new Customer() {Id = 1};
}
}
protected void PostBackButton_Click(object sender, EventArgs e)
{
// Display the Customer ID
Label1.Text = SessionCustomer.Id.ToString();
}