【发布时间】:2011-06-25 19:28:09
【问题描述】:
我的 WCF 服务方法中有一个 try catch 块,其中包含对对象的 if 检查。对象“objRequest”作为服务操作输入参数出现。这是代码:
try
{
if (objRequest == null)
{
//the lines here dont execute even though objRequest is null
...
...
}
//remaining code here
}
catch
{
...
}
现在是奇怪的部分。如果我将 if 检查放在 try 块之外,则 if 检查有效。
if (objRequest == null)
{
//This 'if' check returns true when outside the try block and the line now executes.
.....
....
}
try
{
//remaining code here
}
catch
{
...
}
在此处截取一张图片以证明我在说什么。如果对象为空,为什么要进入 else 块?
我觉得这很神奇,但不是很好。我在这里错过了什么?
【问题讨论】:
-
除此之外,在这种情况下,您可能应该抛出
NullReferenceException而不是一般的Exception。 -
@Dan:你通常不应该抛出
NullReferenceException,而应该抛出ArgumentNullException(如果objRequest是一个参数)或者InvalidOperationException。 -
@user20358:objRequest 不是可为空的类型“int?或 bool?”对吗?
-
if 语句在 try 块内部或外部的计算结果相同。换句话说,你的问题是不正确的。
-
你能发布不适合你的完整代码吗?
标签: c# .net if-statement try-catch