ASP.NET C#布尔型铸造
此代码抛出了一个错误:ASP.NET C#布尔型铸造
bool status1 = (bool)Cache["cache_req_head"];
bool status2 = (bool)Cache["cache_super"];
bool status3 = (bool)Cache["cache_head"];
这是怎样的缓存变量设置:
if (checkreqhead == true)
{
Cache["cache_req_head"] = true;
}
else if (checksuper == true)
{
Cache["cache_super"] = true;
}
else if (checkhead == true)
{
Cache["cache_head"] = true;
}
即将从PHP
的背景下,这是尴尬。错误是:
Object reference not set to an instance of an object
我确定这是一件非常简单的事情,但可能我不能发现它。
感谢所有帮助:)
“不设置到对象的实例对象引用”是C#行话“你做了一件愚蠢的一个null
值”
如果缓存是空的你需要检查第一
bool status1 = (bool)Cache["cache_req_head"];
应该
bool status1 = false;
if (Cache["cache_req_head"] != null)
{
status1 = (bool)Cache["cache_req_head"];
}
这是c#中的值类型(如bool,int等)不能为空的事实的结果。有一个包装,Nullable<T>
与简写T?
,你可以使用,如果你想允许为值类型的空值。
您可以将您的值转换为bool?
,因为它允许null
。
bool? status1 = (bool?)Cache["cache_req_head"];
就可以检查status1 == null
或status1.HasValue
,得到你需要挑选出来与status1.Value
实际布尔值。如果您选择status1.Value
而status1 == null
您将得到一个运行时异常,就像刚才那样。
我还没有尝试过最后一件事,但它会起作用吗?我想你会需要说:布尔? status1 = Cache [“cache_req_head”]为bool? –
@MikeChristensen,我的测试代码'object oBool = null; \t \t \t bool? nBool = oBool as bool? \t \t \t Console.WriteLine(nBool); \t \t \t oBool = false; \t \t \t nBool = oBool as bool?; \t \t \t Console.WriteLine(nBool);'似乎工作正常。 –
@MikeChristensen'as bool'将不起作用,因为'T'需要'T'作为参考类型。 (怎么可能'as',否则返回null时,类型是不正确的?) –
显然,您一次只能设置其中一个缓存条目。所以除非你只用1个变量设置为true来运行“setter”代码3次,那么你总是会返回空值。 null
不会投入bool
,因为它的值类型。尝试使用bool?
由于Cache []返回一个对象,如果未设置,该对象为null,那么您会收到一个异常,试图将null转换为bool。
您必须先检查该键是否存在,或者您必须将每个键设置为“false”作为默认值。
其实,以检查值是否存在在Cache
最好的办法是这样做的:
//string is used as an example; you should put the type you expect
string variable = Cache["KEY"] as string;
if(variable!=null)
{
// do something
}
为什么做if(Cache["KEY"]!=null) myVariable=Cache["Key"];
是不安全的原因,是因为存储在Cache["Key"]
对象可能被删除Cache
,然后才有机会将其分配给myVariable
,并且最终认为myVariable包含非空值。
好点的伴侣 –
顺便说一句:你的if语句中的“== true”是多余的。 – JohnFx