基础知识不扎实,使用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#中所有的类都是引用类型,包括接口。