English 中文(简体)
• 如何把像“阅读”这样的东西包起来?
原标题:How to wrap an int[,] with something like a ReadOnlyCollection?
  • 时间:2009-10-02 14:57:02
  •  标签:

象我这样想:

private int[,] _table = new int[9, 9];
private ReadOnlyCollection<int[,]> _tableReadOnly = new ReadOnlyCollection<int[,]>(_table);

我的想法是让用户看上去哪一种财产——但我不想让它们改变——因此,我认为我可以在这个问题上使用“眼光”。

最佳回答

阅读是一种层面收集。 页: 1 阅读和复制; 重新在线学习和再设计; int;>>,或使您拥有两个层次的总结课程,例如:

public class ReadOnlyMatrix<T> {

   private T[,] _data;

   public ReadOnlyMatrix(T[,] data) {
      _data = data;
   }

   public T this[int x, int y] {
      get {
         return _data[x, y];
      }
   }

}
问题回答

问题在于,你重新尝试把2D的 mu结构总结下来,1D只读到结构。 你们需要几个层次的nes子才能做到这一点。

ReadOnlyCollection<ReadOnlyCollection<int>>

这种做法的倒数不过是,这实际上将迫使你把整个桌上两度记在记忆中。 <代码>ReadOnlyCollection<T>要求作为唯一构造理由的List<T>。 因此,您将把每一行的拷贝复制成一个新的<代码>。 List<int>。

实现这一目的的另一个途径是使用房地产指数器,在不允许变换的情况下直接返还价值。

public int this[int i, int j] {
  get { return _table[i,j]; }
}

这使得消费者能够读到数据,而无需改动。

你可以做这样的事情:

public class ReadOnly2DArray<T>
{
    T[,] _array;
    public ReadOnly2DArray(T[,] arrayToWrap)
    {
        _array = arrayToWrap;
    }

    public T this[int x, int y]
    {
        get { return _array[x, y]; }
    }
}

如果需要,可能增加阿雷尔类的其他方法(Length Property, GetLength方法,......)。

之后,你就使用了这样的东西:

    int[,] a = new int[2, 2];
    ReadOnly2DArray<int> wrapper = new ReadOnly2DArray<int>(a);

    int value = wrapper[0, 0];  // Can read values
    //wrapper[0, 0] = value;      // Won t compile

我并不完全相信我理解你正在采取的方向,但根据你对你再次努力完成的工作所作的描述,我认为你可以做以下工作:

private int[,] _table = new int[9, 9];
public int[,] Table
{
    get
    {
        return _table;
    }
}




相关问题
热门标签