关于List.Contains的问题

Contains比较的是对象还是数据?

public List<Vector3> xx = new List<Vector3> { new Vector3(-4.7f, -96), new Vector3(-4.7f, -136), new Vector3(-4.7f, -176), new Vector3(-4.7f, -216) };
public void Start()
{
    Vector3 x = xx[0];
    bool j = xx.Contains(x);
    Verctor3 y = new Vector3(-4.7f, -96);
    bool k = xx.Contains(x);
    x.x = 4;
    bool i = xx.Contains(x);
    Debug.Log(i + "" + j+""+k);
}

发现,i为false,j为true ,k为true。这里由于Vector3是结构体,属于值类型,所以比较数据。

然后又用一个类MyClass(中间只有一个int x成员)测试,发现比较的不是类成员,而是地址(或者是hashcode?)。因此,就算两个MyClass 对象 a 和 b 的成员x都为0,也是不想等的。

猜你喜欢

转载自blog.csdn.net/skylovecrayon/article/details/79883010