.NET[C#]中NullReferenceException(未将对象引用到实例)是什么问题?如何修复处理?(转)
.NET[C#]中NullReferenceException(未将对象引用到实例)是什么问题?如何修复处理?
郑重申明:本文未经许可,禁止任何形式转载
问题分析
C#中的开发中,如果遇到“NullReferenceException”或者“未将对象引用到实例”这样的提示,那么是你的程序代码正在试图访问一个null的引用类型的实体而抛出的异常。可能的原因有:
情景一 未实例化引用类型实体
忘记了实例化一个引用类型。 在下面的示例中,names声明,但决不实例化:
using System;
using System.Collections.Generic;
public class Example
{
public static void Main(string[] args)
{
int value = Int32.Parse(args[0]);
List<String> names;
names.Add("Major Major Major");
}
}
此例中的 names在使用之前并没有初始化,修复后的:
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<String> names = new List<String>();
names.Add("Major Major Major");
}
}
情景二 泛型连写
如下代码:
ref1.ref2.ref3.member
如果ref1 或者 ref2 或者 ref3任意一个为空时,此代码均会抛出NullReferenceException(未将对象引用到实例)的异常错误。我们可以重写这个表达式来检查以下的r1,r2,r3是否为null:
var r1 = ref1;
var r2 = r1.ref2;
var r3 = r2.ref3;
r3.member
情景三 类的实例未初始化
如下代码:
public class Book {
public string Title { get; set; }
}
public class Example {
public void Foo() {
Book b1;
string title = b1.Title;
}
}
其中,Example类中的b1并未实例化,会抛出NullReferenceException(未将对象引用到实例)异常,解决方法:
使用new关键字来实例化b1对象
修复后的代码:
public class Book {
public string Title { get; set; }
}
public class Example {
public void Foo() {
Book b1 = new Book();
string title = b1.Title;
}
}
情景四 间接引用
如下代码:
public class Person {
public int Age { get; set; }
}
public class Book {
public Person Author { get; set; }
}
public class Example {
public void Foo() {
Book b1 = new Book();
int authorAge = b1.Author.Age;
}
}
这里的 Example 类中的b1已被实例化,但如果我们运行程序,依然会抛出NullReferenceException(未将对象引用到实例)异常。是因为 Book 类中包含了另外一个引用类 Person 但并没有被实例化,解决方式可以在Book的构造器中直接实例化,如:
public class Person {
public int Age { get; set; }
}
public class Book {
public Book(){
Author = new Person();
}
public Person Author { get; set; }
}
public class Example {
public void Foo() {
Book b1 = new Book();
int authorAge = b1.Author.Age;
}
}
当然,你也可以在使用 Book 这个类的实例时再来初始化 Person 这个引用类,如下:
public class Person {
public int Age { get; set; }
}
public class Book {
public Person Author { get; set; }
}
public class Example {
public void Foo() {
Book b1 = new Book();
b1.Author = new Person();
int authorAge = b1.Author.Age;
}
}
情景五 数组为null
int[] numbers = null;
int n = numbers[0];
Person[] people = new Person[5];
people[0].Age = 20
long[][] array = new long[1][];
array[0][0] = 3;
这三种数组的定义均为null,抛出NullReferenceException(未将对象引用到实例)的异常
情景六 数据字典为null
Dictionary<string, int> agesForNames = null;
int age = agesForNames["Bob"];
这里的 agesForNames字典为 null,抛出NullReferenceException(未将对象引用到实例)的异常,使用new关键字来初始化:
Dictionary<string, int> agesForNames = new Dictionary<string, int>();
int age = agesForNames["Bob"];
情景七 集合为null
public class Person {
public string Name { get; set; }
}
var people = new List<Person>();
people.Add(null);
var names = from p in people select p.Name;
string firstName = names.First();
以上代码会在 names.First() 处理抛出异常,因为我们在
people.Add(null);
添加了null值
情景八 事件(Event)为null
public class Demo
{
public event EventHandler StateChanged;
protected virtual void OnStateChanged(EventArgs e)
{
StateChanged(this, e);
}
}
如果外部实例没有注册 StateChanged 事件,那么调用 StateChanged(this, e); 会抛出NullReferenceException(未将对象引用到实例),修复方法:
public class Demo
{
public event EventHandler StateChanged;
protected virtual void OnStateChanged(EventArgs e)
{
if(StateChanged != null)
{
StateChanged(this, e);
}
}
}
情景九 重复的变量名
如果全局变量和局部变量的名称是一样的,那么你的全局变量就可能永远不会被赋值,如下:
public class Form1 {
private Customer customer;
private void Form1_Load(object sender, EventArgs e) {
Customer customer = new Customer();
customer.Name = "John";
}
private void Button_Click(object sender, EventArgs e) {
MessageBox.Show(customer.Name);
}
}
请使用不同的变量名称来修复:
private Customer _customer;
情景二 ASP.NET生命周期
public partial class Issues_Edit : System.Web.UI.Page
{
protected TestIssue myIssue;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// 只有页面首次加载时执行,点击按钮时不会被执行
myIssue = new TestIssue();
}
}
protected void SaveButton_Click(object sender, EventArgs e)
{
myIssue.Entry = "NullReferenceException here!";
}
}
情景十一 ASP.NET Session的值为null
string firstName = Session["FirstName"].ToString();
如果Session[“FirstName”]没有被赋值,则会抛出NullReferenceException(未将对象引用到实例)的异常。
情景十二 ASP.NET 视图模式为null
// Controller[控制器]
public class Restaurant:Controller
{
public ActionResult Search()
{
return View(); // Forgot the provide a Model here.
}
}
// Razor[视图页面]
@foreach (var restaurantSearch in Model.RestaurantSearch) //抛出异常
{
}
<p>@Model.somePropertyName</p> <!-- 抛出异常 -->
关于.NET[C#]中NullReferenceException(未将对象引用到实例)总结到这里,如果你遇到在不同的情景遇到同样的异常,欢迎反馈、交流。
.NET[C#]中NullReferenceException(未将对象引用到实例)是什么问题?如何修复处理?(转)的更多相关文章
- P/Invoke出现错误 System.NullReferenceException”类型的未经处理的异常在 未知模块。 中发生 未将对象引用设置到对象的实例。
问题 “System.NullReferenceException”类型的未经处理的异常在 未知模块. 中发生 未将对象引用设置到对象的实例. 解决方案 1.尝试 用管理员身份运行CMD,输入nets ...
- AutoMapper.Mapper.CreateMap报“System.NullReferenceException: 未将对象引用设置到对象的实例。”异常复现
>>Agenda: >>Ⅰ.国庆假期问题出现 >>Ⅱ.双休日异常再次出现 >>Ⅲ.排障 >>Ⅳ.异常复盘 >>Ⅴ.修复后监测 & ...
- 报警提示 System.NullReferenceException:“未将对象引用设置到对象的实例。
System.NullReferenceException:“未将对象引用设置到对象的实例.是就因为Session在记录到服务器时,没有添加 IRequiresSessionState 所以运行时回 ...
- 让<未将对象引用到实例>见鬼去吧!
未将对象引用到实例,即NullReferenceException异常,我相信这是c#编程中最常见的错误之一,至少我在做项目的过程中,有很多时候都会抛出这个异常.每当这个异常出现的时候,我都会头皮一紧 ...
- Asp.Net MVC 5 Razor 视图 未将对象引用到实例
未将对象引用到实例的错误居然指向了@{Leyout=“..此处略,核实路径无误”}. 最后发现原来是在一个<select .. name="@Model.Category"& ...
- 2014-08-26 解决HttpContext.Current.Session在ashx文件中出现“未将对象引用设置到对象的实例”的问题
今天是在吾索实习的第35天. 最近在使用HttpContext.Current.Session来获取Session["..."]的值时,常常会弹出错误——“未将对象引用设置到对象的 ...
- Server.MapPath(string sFilePath) 报未将对象引用到实例异常
System.Web.HttpContext.Current.Server.MapPath(string sfilePath)将虚拟路径转换成物理路径.这个必须在aspx或者MVC中Action调用才 ...
- C# WinForm程序添加引用后调用静态方法时报“Interfaces_Helper.Global”的类型初始值设定项引发异常。---> System.NullReferenceException: 未将对象引用设置到对象的实例。
出现原因: 因为Global类初始化某个静态变量时没有成功则会抛 System.NullReferenceException 异常,具体代码: public static string connstr ...
- silverlight 报 System.NullReferenceException 未将对象引用设置到对象的实例。
在 Microsoft.Windows.Design.Platform.SilverlightMetadataContext.SilverlightXamlExtensionImplementatio ...
随机推荐
- C#实现短链接生成服务
项目中有一处需求,需要把长网址缩为短网址,把结果通过短信.微信等渠道推送给客户.刚开始直接使用网上现成的开放服务,然后在某个周末突然手痒想自己动手实现一个别具特色的长网址(文本)缩短服务. 由于以前做 ...
- UOJ#276. 【清华集训2016】汽水 二分答案 点分治
原文链接https://www.cnblogs.com/zhouzhendong/p/UOJ276.html 题解 首先,读入的时候就将所有的 $w_i$ 减掉 $k$ . 于是我们要求的就是平均值最 ...
- Spark缓存策略
当对同一个rdd多次执行action时,如果在磁盘上则每次执行action都会从磁盘将数据加载,如果将其缓存到内存中会提高再次action的读取速度,Spark缓存主要有cache()和persist ...
- web服务-2、四种方法实现并发服务器-多线程,多进程,协程,(单进程-单线程-非堵塞)
知识点:1.使用多线程,多进程,协程完成web并发服务器 2.单进程-单线程-非堵塞也可以实现并发服务器 1.多进程和协程的代码在下面注释掉的部分,我把三种写在一起了 import socket im ...
- C#使用CefSharp碰到的坑(一)
使用CEFSharp做模拟提交的话,在高版本下会出现一个神奇的错误: 如果站点使用的是阿里提供的验证控件的话,就是那种拖动条的,如果是使用CEFSharp的新版本的(目前我是测试过70的) ,会出现拖 ...
- npm那些事儿
npm,Node Package Manager,是node.js的模块依赖管理工具,安装nodejs时,一般会附带npm包管理工具. 一.npm相关1.npm的用途 能解决NodeJS代码部署上的很 ...
- Django——RESTful架构
一.REST简述 来自维基百科的解释: 表现层状态转换(REST,英文:Representational State Transfer)是Roy Thomas Fielding博士于2000年在他的博 ...
- Selenium爬取电影网页写成csv文件
绪论 首先写这个文章的时候仅仅花了2个晚上(我是菜鸟所以很慢),自己之前略懂selenium,但是不是很懂csv,这次相当于练手了. 第一章 环境介绍 具体实验环境 系统 Windows10教育版 1 ...
- Mysql概念及基本操作
1.Mysql 概念 1.1 定义 数据库本质是一个C/S的套接字软件 关系型数据库:MySQL mariadb db2 非关系型:存取数据是以key:Value mongodb redis 1.2 ...
- Python中的__init__和__new__
一.__init__ 方法是什么? 使用Python写过面向对象的代码的同学,可能对 __init__ 方法已经非常熟悉了,__init__ 方法通常用在初始化一个类实例的时候.例如: # -*- c ...