【发布时间】:2014-10-03 16:33:33
【问题描述】:
我有一个类在这个类中应该是不可变的,我只有索引器一个私有集属性,所以为什么它不是不可变的,我可以在数组中设置一些字段,就像你在主类中看到的那样......
class ImmutableMatice
{
public decimal[,] Array { get; private set; } // immutable Property
public ImmutableMatice(decimal[,] array)
{
Array = array;
}
public decimal this[int index1, int index2]
{
get { return Array[index1, index2]; }
}
....... 如果我用数据填充这个类并更改数据,则在 main 方法中
static void Main(string[] args)
{
decimal[,] testData = new[,] {{1m, 2m}, {3m, 4m}};
ImmutableMatice matrix = new ImmutableMatice(testData);
Console.WriteLine(matrix[0,0]); // writes 1
testData[0, 0] = 999;
Console.WriteLine(matrix[0,0]); // writes 999 but i thought it should
// write 1 because class should be immutable?
}
}
有什么办法可以让这个类不可变?
是的,解决方案是将数组复制到构造函数中的新数组,如下所示:
public ImmutableMatice(decimal[,] array)
{
decimal[,] _array = new decimal[array.GetLength(0),array.GetLength(1)];
//var _array = new decimal[,] { };
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
_array[i, j] = array[i, j];
}
}
Array = _array;
}
【问题讨论】:
标签: c# arrays class properties immutability