可能出现空引用异常
Resharper 显示“可能的 System.NullReferenceException”警告。然而我不知道如何才能得到一个。
public class PlaceController : PlanningControllerBase
{
[Authorize]
public ActionResult StartStop(int id)
{
if (Request != null && Request.Cookies != null && Request.Cookies["place"] != null)
{
if (Request.Cookies["place"].Value != null)//Possible NullReferenceException?
{
string placeInformation = Request.Cookies["place"].Value;//Possible NullReferenceException?
//...
}
}
}
}
如果我检查所有字段,这如何给出 NullReference?使用以下内容不会显示警告:
Request.Cookies[0];//Index instead of name
编辑:更新的代码。
Resharper is showing a "Possible System.NullReferenceException" warning. I however can't see how I can get one.
public class PlaceController : PlanningControllerBase
{
[Authorize]
public ActionResult StartStop(int id)
{
if (Request != null && Request.Cookies != null && Request.Cookies["place"] != null)
{
if (Request.Cookies["place"].Value != null)//Possible NullReferenceException?
{
string placeInformation = Request.Cookies["place"].Value;//Possible NullReferenceException?
//...
}
}
}
}
How can this give a NullReference if I check all fields? Using the following doesn't show the warning:
Request.Cookies[0];//Index instead of name
Edit: updated code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设检查器不会检查每次传递给 CookieCollection 索引器的字符串值是否相同。我想如果您将代码重组为:
它可能会起作用。
I assume the checker isn't checking the value of the string passed to the CookieCollection indexer is the same each time. I imagine if you restructure the code to:
It might work.
您不需要听取每一个警告。
Request
对象和Cookies
对象永远不会为 null,因此这就是您所需要的。You don't need to listen to every single warning. The
Request
object and theCookies
object will never be null so this is all you need.呃,你不想
Request.Cookies["place"].Value != null
,现在您只需将 placeInformation 设置为 null。
err don't you want
Request.Cookies["place"].Value != null
, right now you will only be setting placeInformation to null.