C# List 使用陷阱

基礎知識不紮實,使用List<T>,出現意料之外的結果

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

namespace testlist
{
    public class PointD//點類
    {
        public double X;
        public double Y;

        public PointD(double x, double y)
        {
            X = x;
            Y = y;
        }
        public PointD()
        {

        }

    }
    class Program
    {
        static void Main(string[] args)
        {

            List<PointD> lstPoints = new List<PointD>();
            PointD pD = new PointD(1.0, 1.0);
            lstPoints.Add(pD);
            lstPoints.Add(pD);
            lstPoints.Add(pD);
            lstPoints.Add(pD);
            for (int i = 0; i < lstPoints.Count; i++)
            {
                lstPoints[i].Y += 1.0;
            }
            lstPoints.ForEach(i => Console.WriteLine(i.Y));
            Console.ReadLine();
        }
    }
}

按自己的意料應該輸出 :

2

3

4

5

實際結果卻是:

5

5

5

5

原來是自己基礎知識不夠紮實導致這樣的理解錯誤,也怪自己靜不下心去鑽研C#知識,實際也沒有時間精力,也沒耐心去學習,心裏有想法就匆匆開寫代碼。配合宇宙最強IDE-vs的C#當然是首選,這不程序出現bug了才發現基礎知識的重要。

關鍵在於List<T>的T是值類型還是引用類型。

  • 什麼是值類型:
    • 抽象類型System.ValueType的直接派生類,System.ValueType從System.Object派生的。所有的值類型都從System.ValueType派生,所有的枚舉都從System.Enum抽象類派生,而後者又從System.ValueType派生。  
    •  所有的值類型都是隱式密封的(sealed),防止其他任何類型從值類型進行派生。       
  • 什麼是引用類型:
    • 在c#中所有的類都是引用類型,包括接口。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章