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

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

        }
    }
}


 


 

相关文章
|
10月前
|
算法 Java 程序员
JVM-如何判断对象可以回收
JVM-如何判断对象可以回收
|
4月前
|
设计模式
在静态方法中访问类的实例属性和方法时会发生什么?
总之,静态方法主要用于处理与类本身相关的操作和逻辑,不应该直接访问类的实例属性和方法。如果需要在静态方法中使用与实例相关的信息,应该通过合理的参数传递或其他设计模式来实现,以保持代码的清晰性和面向对象设计的原则。
91 8
|
5月前
|
存储 编译器 C++
【C++】掌握C++类的六个默认成员函数:实现高效内存管理与对象操作(二)
【C++】掌握C++类的六个默认成员函数:实现高效内存管理与对象操作
|
5月前
|
存储 编译器 C++
【C++】掌握C++类的六个默认成员函数:实现高效内存管理与对象操作(三)
【C++】掌握C++类的六个默认成员函数:实现高效内存管理与对象操作
|
5月前
|
存储 编译器 C++
【C++】掌握C++类的六个默认成员函数:实现高效内存管理与对象操作(一)
【C++】掌握C++类的六个默认成员函数:实现高效内存管理与对象操作
|
8月前
|
存储 缓存 算法
同时使用线程本地变量以及对象缓存的问题
【7月更文挑战第15天】同时使用线程本地变量和对象缓存需小心处理以避免数据不一致、竞争条件及内存泄漏等问题。线程本地变量使各线程拥有独立存储,但若与对象缓存关联,可能导致多线程环境下访问旧数据。缺乏同步机制时,多线程并发修改缓存中的共享对象还会引起数据混乱。此外,若线程结束时未释放对象引用,可能导致内存泄漏。例如,在Web服务器场景下,若一更新缓存而另一线程仍获取旧数据,则可能返回错误信息;在图像处理应用中,若多线程无序修改算法对象则可能产生错误处理结果。因此,需确保数据一致性、避免竞争条件并妥善管理内存。
|
10月前
|
存储 安全 Java
Python中的引用和赋值机制允许变量引用内存中的对象,并通过引用计数来管理对象的生命周期
【5月更文挑战第14天】Python中的变量是对象引用,不存储数据,而是在内存中创建对象。赋值操作创建新变量并使其指向已有对象。引用计数用于管理对象生命周期,引用数为0时对象被回收。理解这些机制对编写高效Python代码很重要。
84 6
|
10月前
|
安全 编译器 C++
C++类与对象【对象的初始化和清理】
C++类与对象【对象的初始化和清理】
|
10月前
|
算法 Java
JVM中判断对象是否需要回收的方法
JVM中判断对象是否需要回收的方法
对象的相等和引用相等的区别
对象的相等和引用相等的区别