C# 未将对象引用设置为对象的实例 #3
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/901063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
object reference not set to an instance of an object #3
提问by Prasad
I am getting the object reference error in just start of the method.
我在方法刚开始时就收到了对象引用错误。
For Ex.:
例如:
259: public ActionResult ShowAddress(FormCollection formCollection)
260: {
In the above sample i am getting the error Line number 260.
在上面的示例中,我收到错误行号 260。
采纳答案by JaredPar
Here is the code from the question comments
这是问题评论中的代码
259: public ActionResult ShowAddress(FormCollection formCollection) {
260: long _userId= long.Parse(formCollection["UserId"].ToString());
261: UserDetails _userDetails = _userDAL.GetUserDetails(_userId);
262: if(!string.IsNullOrEmpty(_userDetails.Address1)) return RedirectToAction("GetAddress", "User"); else return View(); }
If you're seeing a NullReferenceException at line 260, either formCollection or the result of formCollection["UserId"] is null. You need to account for this in your code. For instance you could do the following.
如果您在第 260 行看到 NullReferenceException,则 formCollection 或 formCollection["UserId"] 的结果为 null。您需要在代码中考虑到这一点。例如,您可以执行以下操作。
public ActionResult ShowAddress(FormCollection formCollection) {
if ( null == formCollection ) {
return View();
}
object obj = formCollection["UserId"];
if ( null == obj ) {
return View();
}
long _userId = long.Parse(obj.ToString());
...
}
回答by corlettk
Finally, Enough information to attempt to post an answer...
最后,有足够的信息尝试发布答案......
I suppose formCollection must be null.
我想 formCollection 必须为空。
PS: You'd benifit from reading this: http://catb.org/esr/faqs/smart-questions.html#introThink of it as a life investment in life assurance.
PS:您会从阅读本文中受益:http: //catb.org/esr/faqs/smart-questions.html#intro将其视为对人寿保险的人寿投资。