对象引用不设置到对象的实例 - 解释? [英] Object reference not set to an instance of an object - explanation?

查看:131
本文介绍了对象引用不设置到对象的实例 - 解释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找的步骤/指导,解决错误对象引用未设置到对象的实例。为什么会出现这个问题的解释。

I am looking for steps/guidance to troubleshoot the error Object reference not set to an instance of an object. and an explanation of why the issue occurs.

我要寻找一个更一般的解释,所以如果我得到的错误,我应该找什么问题的步骤。我经常看到的帖子,其中有人提供了一段特定的code,和其他人将提供固定的code(有时)。如果提供简单的code的例子来说明这个问题,这很好。

I am looking for a more general explanation, so if I get the error, what steps I should take to find the problem. I often see posts where someone provides a specific piece of code, and someone else will provide the fixed code (sometimes). If simple code examples are provided to illustrate this problem, that's fine.

我需要一个高层次的解释。

I need a high level explanation.

推荐答案

要解释它的最简单的方法是,如果你的对象引用(你的变量)是,然后你不能没有触发该异常访问它的任何属性或方法。下面是code为例,将抛出一个空参考异常(因为他们是所谓):

The easiest way to explain it is that if your object reference (your variable) is null, then you can't access any properties or methods on it without triggering that exception. Here's an example of code that would throw a "Null Ref" exception (as they are called):

string s = null;
int leng = s.Length;

所以我定义了一个字符串,但随后尝试访问其<$​​ C $ C>长属性。发生的异常。如果我用的一个方法 字符串的ToString(),除了会发生为好。

So I define a string as null, but then try to access its Length property. The exception occurs. If I had used a method on that null string like ToString(), the exception would happen as well.

通过跟踪沿着这条错误的问题是,你可以从错误文本看,你看不出来马上对空参考的地方出现。你必须在一个断点异常发生前将走在code,直到你发现有问题的作品。

The problem with tracing down this error is that, as you can see from the error text, you can't tell right away where the Null Ref has occurred. You'll have to put in a breakpoint before the exception occurs and walk the code until you find the offending piece.

这篇关于对象引用不设置到对象的实例 - 解释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆