The main purpose of this article is to briefly discuss the list operation process for memory in C #, so that you can avoid mistakes in this case in the future. The content is very simple, but it is used as a record here. It is the best to help people. If you cannot help, you should wake yourself up. C # hides all complex pointer operations in the background for processing, so that we can see the essence of C.
In C #, list <t> List = new list <t> (); the new process creates a memory space and creates an empty list object without elements.
List in C. clear () is to clear the content of the new memory space. It is not to delete this memory space. It is to clear the elements of the original list object or the object, and the element is gone.
Next, let's take a look at the situations in which the program encounters an exception bug due to misuse of clear.
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 <objectmouse> list1 = new 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 (); // use the clear () method to output figure 1
// List = new list <objectmouse> (); // use new to output figure 2
While (flag <2)
{
Mouse. Name = "Mouse ";
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 ("---------------- gorgeous split line -------------------");
}
Console. readkey ();
}
}
}
Figure 1 Figure 2