集合类操作:未将对象引用设置到对象的实例

简介: 以List为例,具体错误信息如下: 未处理 System.NullReferenceException Message=未将对象引用设置到对象的实例。 Source=TestSet StackTrace: 在 TestSet.Form1.button1_Click(Object sender, EventArgs e) 位置 E:\WorkSpace\VS201

以List为例,具体错误信息如下:

未处理 System.NullReferenceException
  Message=未将对象引用设置到对象的实例。
  Source=TestSet
  StackTrace:
       在 TestSet.Form1.button1_Click(Object sender, EventArgs e) 位置 E:\WorkSpace\VS2010\TestSet\TestSet\Form1.cs:行号 34
       在 System.Windows.Forms.Control.OnClick(EventArgs e)
       在 System.Windows.Forms.Button.OnClick(EventArgs e)
       在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       在 System.Windows.Forms.Control.WndProc(Message& m)
       在 System.Windows.Forms.ButtonBase.WndProc(Message& m)
       在 System.Windows.Forms.Button.WndProc(Message& m)
       在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       在 System.Windows.Forms.Application.Run(Form mainForm)
       在 TestSet.Program.Main() 位置 E:\WorkSpace\VS2010\TestSet\TestSet\Program.cs:行号 18
       在 System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       在 System.Threading.ThreadHelper.ThreadStart()
  InnerException: 


先声明一个类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestSet
{
     public class Test
    {
        public Test()
        { 
        //
        }
        private List<TestChild> _TestChilds;
        /// <summary>
        /// 子类 
        /// </summary>
        public List<TestChild> TestChilds
        {
            set { _TestChilds = value; }
            get { return _TestChilds; }
        }
    }
}


子类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestSet
{
    public class TestChild
    {
        public TestChild()
        { }
        private string _TestChildsId;
        public string TestChildsId
        {
            set;
            get;
        }
        private string _TestChildsName;
        public string TestChildsName
        {
            set;
            get;
        }
        private string _TestChildsCount;
        public string TestChildsCount
        {
            set;
            get;
        }
    }
}

在测试Form窗体添加如下代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestSet
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Test ts = new Test();
            for (int i = 0; i < 10; i++)
            {
                TestChild tsc = new TestChild();
                tsc.TestChildsCount = "10";
                tsc.TestChildsId = Guid.NewGuid().ToString();
                tsc.TestChildsName = "name";

                ts.TestChilds.Add(tsc);
            }
            int ss = ts.TestChilds.Count;
        }
    }
}


小注:这个错误在操作集合类Collection、List时,均会出现,原因是:Test类的属性没有实例化,在添加数据之前给它实例化一下,具体代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestSet
{
    public class Test
    {
        public Test()
        {
            //
        }
        private List<TestChild> _TestChilds;
        /// <summary>
        /// 子类 
        /// </summary>
        public List<TestChild> TestChilds
        {
            //以下代码为修正代码
            get
            {
                if (_TestChilds == null)
                {
                    _TestChilds = new List<TestChild>();
                }
                return _TestChilds;
            }
            set
            {
                _TestChilds = value;
            }

        }
    }
}


 


 

目录
相关文章
|
前端开发 JavaScript 应用服务中间件
虚拟机项目部署与发布
虚拟机项目部署与发布
478 0
|
C++
UE4/5中DataTable数据表的使用
UE4/5中DataTable数据表的使用
1555 1
UE4/5中DataTable数据表的使用
|
数据安全/隐私保护 Docker 容器
docker版Minio接入LDAP
因为官网的LDAP文档接入写的过于分散,实在不利于新手部署,所以重新整理了一版,方便用户能一次部署完成
2579 1
docker版Minio接入LDAP
|
4月前
|
安全 开发工具 开发者
仓颉编程语言(Cangjie)正式发布1.0.0 LTS版本,附安装配置教程
仓颉编程语言首个长期支持版本于2025年7月1日发布,定位为面向全场景应用开发的下一代语言。其特点包括多后端支持、简明语法、多范式编程、类型与内存安全、高效并发及丰富内置库。支持与C语言互操作,并提供元编程能力,助力UI开发。当前仅提供CJNative后端SDK,配套VS Code插件便于开发。安装包已规范命名,可在官网下载并按指导完成配置。
1080 1
仓颉编程语言(Cangjie)正式发布1.0.0 LTS版本,附安装配置教程
|
7月前
|
前端开发 API 开发工具
一年撸完百万行代码,企业微信的全新鸿蒙NEXT客户端架构演进之路
本文将要分享的是企业微信的鸿蒙Next客户端架构的演进过程,面对代码移植和API不稳定的挑战,提出了DataList框架解决方案。通过结构化、动态和认知三重熵减机制,将业务逻辑与UI解耦,实现数据驱动开发。采用MVDM分层架构(业务实体层、逻辑层、UI数据层、表示层),屏蔽系统差异,确保业务代码稳定。
333 0
|
11月前
|
SQL 弹性计算 安全
在云上轻松部署达梦数据库
达梦数据库(DM Database)是达梦数据库有限公司开发的关系型数据库管理系统,广泛应用于政府、金融、能源等行业。它具备高性能、高安全、兼容性强、易管理等特点,支持多种操作系统,适用于关键业务系统、政务系统及大数据处理等场景。在阿里云上,可通过一键部署快速使用达梦数据库DM8。
|
关系型数据库 MySQL 数据库
如何使用Docker部署MySQL数据库?
【10月更文挑战第1天】如何使用Docker部署MySQL数据库?
636 0
|
并行计算 PyTorch 算法框架/工具
LLM推理引擎怎么选?TensorRT vs vLLM vs LMDeploy vs MLC-LLM
有很多个框架和包可以优化LLM推理和服务,所以在本文中我将整理一些常用的推理引擎并进行比较。
1968 2
|
安全 网络协议 网络安全
HTTPS 存在哪些安全问题,有什么应对方案
HTTPS 是 HTTP 的安全版本,通过使用 SSL/TLS 协议对通信内容进行加密,提供了以下几个关键的安全特性:数据加密、身份认证和完整性保护。尽管 HTTPS 在很大程度上提高了安全性和数据传输的安全性,但仍然存在一些潜在的安全问题。以下是一些可能的问题以及相应的应对方案
|
域名解析 JSON 网络协议
freeipa安装部署
freeipa是linux的一个开源的安全解决方案,它提供账户管理和集中认证,类似于微软的AD(active directory)。
4105 0