在C#中仅读取二维数组 [英] Read only two-dimensional array in C#

查看:183
本文介绍了在C#中仅读取二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有建立返回C#中只读二维数组的方法?

Is there any established way of returning a read-only 2-d array in C#?

我知道ReadOnlyCollection是用于一维数组的正确方法,并且很高兴编写自己的实现this[] {get}的包装器类.但是如果这个轮子已经存在,我不想重新发明轮子.

I know ReadOnlyCollection is the right thing to use for a 1-d array, and am happy to write my own wrapper class that implements a this[] {get}. But I don't want to reinvent the wheel if this wheel already exists.

推荐答案

只有一种方法可以模拟这种情况.

There's only one way to simulate this.

您需要使用私有数组创建自己的类.

You need to create your own class, with a private array.

与数组最相似的实现是索引器:

The most similar implementation of an array is an indexer:

  • Using indexers
  • Indexers (C# programming guide)
  • 10.8 Indexers (old)
  • C# 6.0 draft Indexers

"10.8"链接显示了二维数组的模拟.

The '10.8' link shows the simulation of a bidimensional array.

如果仅使用getter来实现索引器,则用户只能读取元素,而不能写入元素.但是,如果每个元素都是一个对象(引用类型),则不能阻止修改所访问的对象的属性.

If you implement the indexer only with a getter, the user can only read the elements, but not write them. However, if each element is an object (reference type) you can't prevent the modification of the accessed objects properties.

但是,有几种模拟只读"对象的方法:

However, there are several ways of simulating "read-only" objects:

  • 创建一个包装器类,将包装中每个元素的属性公开为只读属性,以便无法对其进行修改
  • 使用原始值类型(例如int)
  • 通过返回私有数组中元素的副本而不是私有数组中的原始元素来对更改进行伪造,这样,对该对象所做的更改不会影响数组中的原始对象.

在其他语言(如C ++)中,有指向常量值的引用和指针,但这在C#中不存在.

In other languages like C++ there are references and pointers to constant values, but this doesn't exist in C#.

这篇关于在C#中仅读取二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆