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

简介: 以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;
            }

        }
    }
}


 


 

相关文章
|
1月前
|
存储 Java
|
2月前
|
前端开发 算法 JavaScript
检查是否是类的对象实例
检查是否是类的对象实例
16 0
|
2月前
|
安全 编译器 C++
C++类与对象【对象的初始化和清理】
C++类与对象【对象的初始化和清理】
C++类与对象【对象的初始化和清理】
|
6月前
|
Java
对象的相等和引用相等的区别
对象的相等和引用相等的区别
|
11月前
|
安全 编译器 数据安全/隐私保护
对象的动态创建和销毁以及对象的复制,赋值
🐰对象的动态创建和销毁 🐰对象的复制 🐰对象的赋值
玩转JVM中的对象及引用:从创建到引用到分配和优化策略
类加载检查 当Java虚拟机遇到一条new指令的时候,它会先去运行时常量池中寻找new的类的符号引用,并且检查这个符号引用所代表的类是否已经被加载、解析、初始化过。如果没有即需要进行相应的类加载过程。
|
开发者 索引 Python
对象操作2|学习笔记
快速学习对象操作2
48 0
对象操作2|学习笔记
|
安全 编译器 C++
C++对象的初始化和清理之构造函数和析构函数分析与实例(一)
对象的初始化和清理 • 生活中我们买的电子产品都基本会有出厂设置,在某一天我们不用时候也会删除一些自己信息数据保证安全 • C++中的面向对象来源于生活,每个对象也都会有初始设置以及 对象销毁前的清理数据的设置。 构造函数和析构函数 对象的初始化和清理也是两个非常重要的安全问题 一个对象或者变量没有初始状态,对其使用后果是未知
339 0
C++对象的初始化和清理之构造函数和析构函数分析与实例(一)
|
存储 JavaScript 前端开发
访问对象的属性,你知道有哪些方法?
相信对象对于每个使用JavaScript的人来说都不陌生。访问对象的属性几乎日常开发每天都在用。下面我们一起探索下有哪些方式可以实现属性的访问。
150 0
|
Java
千万不要再这样创建集合了!极容易内存泄露!
由于Java语言的集合框架中(collections, 如list, map, set等)没有提供任何简便的语法结构,这使得在建立常量集合时的工作非常繁索。
314 0