码迷,mamicode.com
首页 > 其他好文 > 详细

C#中List<object>.Clear()方法和实例化new List<object>()操作的结果分析

时间:2014-07-24 21:57:12      阅读:1685      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   strong   io   width   

    本文主要的目的是想简单的探讨一下C#中List针对内存的操作过程,以便以后遇到该种情况可以避免走进误区,内容非常简单,只是在此作为记录。能帮到人最好,帮不到就当给自己提个醒。C#将复杂的指针操作全都隐藏到后台去处理,以至于是我们很到看到C#的本质。

C#中list<T> list=new List<T>();中new的过程是建立一块内存空间,是新建一个没有元素的空列表对象。

C#中list.Clear()是把new之后的那块内存空间的内容清空,并不是删除这块内存空间,是清除原先列表对象的元素,还是那个对象,元素没了。

下面就说一下在哪种情况下会因为误用clear导致程序出现异常bug。

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

namespace listAndnew
{
    public class objectmouse
    {
        public string Name { get; set; }
        public bool Sex { get; set; }
        public int Age { get; set; }
    }
    class Program
    {
        static List<objectmouse> list = new List<objectmouse>();
        static List<List<objectmouse>> list1 = new List<List<objectmouse>>();
        static Random seed = new Random();

        static void Main(string[] args)
        {
            int a = 0;
            while (a < 2)
            {
                int flag = 0;
                objectmouse mouse = new objectmouse();
                list.Clear();///////////使用clear()方法输出图1
                //list = new List<objectmouse>();/////////////使用new输出图2

                while (flag < 2)
                {
                    mouse.Name = "小白鼠";
                    mouse.Age = seed.Next(20);
                    mouse.Sex = true;
                    list.Add(mouse);
                    flag++;
                }

                list1.Add(list);
                a++;
            }
            for (int i = 0; i < list1.Count; i++)
            {
                for (int j = 0; j < list.Count; j++)
                {
                    Console.WriteLine("Name" + list1[i][j].Name + "Sex:" + list1[i][j].Sex + "Age:" + list1[i][j].Age);

                }
                Console.WriteLine("----------------华丽的分割线-------------------");
            }

            Console.ReadKey();

        }
    }
}

bubuko.com,布布扣bubuko.com,布布扣

                     图1                                        图2

C#中List<object>.Clear()方法和实例化new List<object>()操作的结果分析,布布扣,bubuko.com

C#中List<object>.Clear()方法和实例化new List<object>()操作的结果分析

标签:style   blog   http   color   使用   strong   io   width   

原文地址:http://www.cnblogs.com/jiangxin/p/3866015.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!