List的add方法剖析
Class1:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace new一個例項
{
public class Class1
{
public int i { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace new一個例項
{
class Program
{
static void Main(string[] args)
{
//var c2=new List<Class1>();
//Class1 c1 = new Class1();
//for (int i = 0; i < 100; i++)
//{
// c1.i = i;
// c2.Add(c1);
//}
//foreach (var c in c2)
//{
// Console.WriteLine(c.i.ToString());
//}
//---------------------------------
//var c2 = new List<Class1>();
//Class1 c1 = new Class1();
//for (int i = 0; i < 100; i++)
//{
// c1.i = i;
// c2.Add(c1);
//}
//foreach (var c in c2)
//{
// Console.WriteLine(c.i.ToString());
//}
Console.ReadKey();
}
}
}
兩段程式碼輸出結果理解list的add院裡
其實add時候並不是複製了值,而是傳遞了地址,所以
//var c2 = new List<Class1>();
//Class1 c1 = new Class1();
//for (int i = 0; i < 100; i++)
//{
// c1.i = i;
// c2.Add(c1);
//}
//foreach (var c in c2)
//{
// Console.WriteLine(c.i.ToString());
//}
Console.ReadKey();
}
}這裡的輸出結果全都是99,希望會對大家有幫助