当前位置: 代码迷 >> C# >> C# list .add()“未将对象引用设置到对象的实例。”解决方案
  详细解决方案

C# list .add()“未将对象引用设置到对象的实例。”解决方案

热度:46   发布时间:2016-05-05 04:04:00.0
C# list .add()“未将对象引用设置到对象的实例。”
首先我定义两个类,虽然这两个类不是太规范我觉得还是能用的
public  class TPoint
    {
        public int x;
        public int y;
        public int z;
        public TPoint()
        {
            x = 0;
            y = 0;
            z = 0;
        }
        public TPoint(int a, int b, int c)
        {
            x = a;
            y = b;
            z = c;
        }
     
  
    }
public class Surface
    {
       public List<TPoint> Simppoint = new List<TPoint>();
       public Surface()
       {
           
       }
    }
然后我从一个txt  文档你们读取数据
里面数据类似    12   45   1
                            22   88   1
                            ......................
class Doc
    {
        public Surface[] surface = new Surface[100];
        public int number;
        public Doc()
        {
            FileStream fs = new FileStream(@"D:\a.txt", FileMode.Open);
            StreamReader sr = new StreamReader(fs); 
            string tpoint;
            int i = 0;
            int N;
           
            while ((tpoint = sr.ReadLine()) != null)
            {

                TPoint tp = new TPoint();
                for (i = 0; tpoint[i] != ' '; i++)
                {
                    tp.x = tp.x * 10 + tpoint[i] - '0';
                    //surface[N].point[surface[N].length].x=surface[N].point[surface[N].length].x*10+(tpoint[i]-'0');
                }
                for (i++; tpoint[i] == ' '; i++)
                {
                }
                for (; tpoint[i] != ' '; i++)
                {
                    tp.y = tp.y * 10 + tpoint[i] - '0';
                    //surface[N].point[surface[N].length].y=surface[N].point[surface[N].length].y*10+(tpoint[i]-'0');
                }
                for (i++; tpoint[i] == ' '; i++)
                {
                }
                for (; i < tpoint.Length; i++)
                {
                    tp.z = tp.z * 10 + tpoint[i] - '0';
                    //surface[N].point[surface[N].length].z=surface[N].point[surface[N].length].z*10+(tpoint[i]-'0');
                }
                N = tp.z;
                surface[N].Simppoint.Add(tp);//每次程序运行到这里就发生中断异常
                number = N;
            }
            sr.Close();
           
        }
  每次程序运行到这里就发生中断异常  surface[N].Simppoint.Add(tp);+ 已引发:“未将对象引用设置到对象的实例。”(System.NullReferenceException) 异常消息 = "未将对象引用设置到对象的实例。", 异常类型 = "System.NullReferenceException", 异常 WinRT 数据 = ""
真心很急,求大神指教
------解决思路----------------------
surface 没有实例化
你断点跟,只不过是定义了长度为100的空数组,里面都是null

既然已经定义了list,怎么还定义数组?是想闹哪样
------解决思路----------------------
确切的说,是surface[N]是null
你需要先surface[N]=new Surface();
才行
  相关解决方案