readonly list overriding self

时间:2017-05-20 12:23:55

标签: c# list readonly

我有一个包含几个坐标的只读列表。

private readonly List<float[]> rightPositions = new List<float[]>()
{
    new float[2] { 250, 0 },
    new float[2] { 350, -200 },
    new float[2] { 350, 200 },
    new float[2] { 600, 0 }
};

在以下方法中,我将List<float[]> rightPositions的静态数据提供给字段rTeam.PlayerArray[iterator].Position

private void ClearPlayers(Team rTeam, Team lTeam)
    {
        for (int iterator = 0; iterator < rTeam.PlayerArray.Length; iterator++)
        {
            rTeam.PlayerArray[iterator].Position = rightPositions.ElementAt(iterator);
        }  
    }

首次执行ClearPlayers(Team rTeam, Team lTeam)时,List<float[]> rightPositions中的数据会被放入rTeam.PlayerArray[iterator].Position。在第一次之后,只读List<float[]> rightPositions中的数据与之前的数据不同。

我错过了一些明显的东西吗?或者我是否需要使用els而不是readonly字段?

提前致谢。

2 个答案:

答案 0 :(得分:0)

readonly仅表示&#34;您无法更改此变量的值。&#34;您可以更改列表中的任何内容,但无法创建新列表。

它也不会改变实际内容的工作方式。您创建浮点数组,将它们分配到某个位置,它们仍指向同一个数组,因此您对它们所做的任何更改都将影响此列表中的数组。

如果要防止数组发生变化,则必须克隆数组。

rTeam.PlayerArray[iterator].Position = (float[])rightPositions.ElementAt(iterator).Clone();

另一种方法是使用struct,因为我假设Position具有X和Y坐标,因此使用X和Y struct然后分配将更合乎逻辑复制数据,而不是在源中以任何方式更改它。它也很可能使代码更清晰。

答案 1 :(得分:0)

List不是只读的。 List无法为只读。它的属性是只读的。这意味着您无法为该属性分配不同的List对象,但是一旦从属性中获取List对象,它就像任何其他List一样,所以你可以随意修改它。如果您希望该集合为只读,请使用ReadOnlyCollection而不是List