简体   繁体   English

你调用的对象是空的

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

When I try to open the page from my IDE in VS 2008 using "VIEW IN BROWSER" option I get "Object reference not set to an instance of an object" error. 当我尝试使用“VIEW IN BROWSER”选项从VS 2008中的IDE打开页面时,我得到“对象引用未设置为对象的实例”错误。

The piece of code I get this error : 这段代码我得到这个错误:

 XResult = Request.QueryString["res"];    
 TextBox1.Text = XResult.ToString();

The problem here is that XResult is null and when you call ToString on it the code produces a NullReferenceException . 这里的问题是XResultnull ,当你在其上调用ToString时,代码会产生NullReferenceException You need to account for this by doing an explicit null check 您需要通过执行显式null检查来解释此问题

TextBox1.Text = XResult == null ? String.empty : XResult.ToString();

If you are opening the page without the "res" query string then you need to include a check for null before you do anything with it. 如果您打开没有“res”查询字符串的页面,那么在对它执行任何操作之前,您需要包含对null的检查。

if (Request.QueryString["res"] != null)
{
    XResult = Request.QueryString["res"];
    TextBox1.Text = XResult.ToString();
}

这个错误可能是因为REquest.QueryString方法没有在url中找到“res”的值,所以当你尝试对一个空对象执行“toString”时,该对象执行该操作。

Your code is expecting a query string http://localhost:xxxx/yourapp?res=yourval . 您的代码需要查询字符串http://localhost:xxxx/yourapp?res=yourval It's not present in the address supplied to the browser. 它不存在于提供给浏览器的地址中。 In the web section of your project properties, you can supply an appropriate URL. 在项目属性的Web部分中,您可以提供适当的URL。 Of course, shoring up your code to allow for this would be advisable. 当然,为了实现这一目的,支持你的代码是可取的。

The problem here is that XResult is null, and when you call ToString on it the code produces a NullReferenceException . 这里的问题是XResult为null,当你在其上调用ToString时,代码会产生NullReferenceException You need to account for this by doing an explicit null check: 您需要通过执行显式空检查来解释此问题:

if (Request.QueryString["res"] != null)
{
    XResult = Request.QueryString["res"];
    TextBox1.Text = XResult.ToString();
}

XResult is already a string, so calling ToString isn't necessary. XResult已经是一个字符串,因此不需要调用ToString。 That should also fix your problem. 这也应该解决你的问题。

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

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