简体   繁体   English

对象引用未设置为对象错误消息的实例

[英]Object reference not set to an instance of an object error message

What is wrong with my code? 我的代码有什么问题? I recently posted a question about Calculation in code behind and I tried Vinoth's answer but it gives me an error at this line: 我最近在后面的代码中发布了一个关于“ 计算”的问题,我尝试了Vinoth的答案,但这在这一行给了我一个错误:

bool isChaffeurUsed = (bool)Session["IsChaffeurUsed"];

error message is: Object reference not set to an instance of an object. 错误消息是: 对象引用未设置为对象的实例。

Please tell me what should i do. 请告诉我该怎么办。 Many thanks and have a nice day. 非常感谢,祝您有愉快的一天。

Session["IsChaffeurUsed"]

Is not defined - you haven't set any session variable with the key IsChaffeurUsed 未定义-您尚未使用键IsChaffeurUsed设置任何会话变量

You need to check if it's set first, 您需要检查是否已设置第一项,

bool isChaffeurUsed;

if(Session["IsChaffeurUsed"] != null)
    isChaffeurUsed = (bool)Session["IsChaffeurUsed"];

You need to check the object first, try: 您需要先检查对象,然后尝试:

var isChaffeurUsed = false;

if (Session["IsChaffeurUsed"] != null)
{
    isChaffeurUsed  = bool.Parse(Session["isChaffeurUsed"].ToString());
}

The error is trying to tell you that Session["IsChaffeurUsed"] doesn't exist. 该错误试图告诉您Session["IsChaffeurUsed"]不存在。

If you know a default value, you could change the statement to read: 如果您知道默认值,则可以将语句更改为:

bool isChaffeurUsed = (bool)(Session["IsChaffeurUsed"] ?? false)

Or, if you want to allow null values (which would indicate that the value wasn't set specifically to any value), you could use a nullable type: 或者,如果您想允许使用空值(这表示该值未专门设置为任何值),则可以使用可空类型:

bool? isChaffeurUsed = (bool?)Session["IsChaffeurUsed"];

最有可能的是,您在Session没有任何名称为"IsChaffeurUsed"

You would get that exception if Session was null or if IsChaffeurUsed was not found in Session. 如果Session为null或在Session中找不到IsChaffeurUsed,则会得到该异常。 Session is probably not null, so the problem is likely that IsChaffeurUsed is not found. 会话可能不为null,因此可能会出现找不到IsChaffeurUsed的问题。

You need to decide what to do if the IsChaffeurUsed was not set. 如果未设置IsChaffeurUsed,则需要决定如何处理。 For example, you could assume it's false: 例如,您可以假设它是错误的:

bool isChaffeurUsed = Session["IsChaffeurUsed"] == null ? false 
     : (bool)Session["IsChaffeurUsed"];

由于以下原因存在TryParse()方法:

bool.TryParse(Session["IsChaffeurUsed"], out isChaffeurUsed)

One thing about looking at session variables is that there's a possibility the variable will be gone after the initial read (this has happened to me on a few occasions). 查看会话变量的一件事是,变量在初次读取后很可能会消失(这在我身上有几次发生)。 This is usually the pattern I use when dealing with looking at session/cache variables in an ASP app: 这通常是我在ASP应用程序中查看会话/缓存变量时使用的模式:

object o = null;
if((o = Session["IsChaffeurUsed"]) != null)
{
    // Do something with o: bool.Parse, (bool), etc...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM