繁体   English   中英

有没有更好的方法封装数组?

[英]Is there any better way to encapsulate an array?

我目前的工作方式:

class Foo
{
    public int[] A { get { return (int[])a.Clone(); } }
    private int[] a;
}

我认为这很糟糕,因为它会创建一个克隆并在我访问它时进行强制转换。 我知道我可以通过引入这样的附加变量来解决它

var foo = new Foo();
// as soon as you have to access foo.A do this
int[] fooA = foo.A;
// use fooA instead of foo.A from now on

但仍然看起来很糟糕。

我也不喜欢Java的封装方式

int get(int index) { return a[index]; }

因为我没有获得使用数组的优势。

有什么更好的方法吗?

编辑:我想要一个封装变量的数组。 问题是

public int[] A { get; private set; }

不是封装变量的数组,因为我可以从类外部修改数组的元素。

编辑:它也应该与多维数组一起使用

数组实现了IReadOnlyList<T> ,它公开了您想要的所有相关信息(迭代器,索引器,计数等),而没有公开数组的任何可变功能。

class Foo
{
    public IReadOnlyList<int> A { get { return a; } }
    private int[] a;
}

或者,您可以使用迭代器/生成器按要求返回项目:

class Foo
{
    public IEnumerable<int> A
    {
        get
        {
            foreach (int i in a)
                yield return i;
        }
    }
    private int[] a;
}

...然后通常对其进行迭代,或使用LINQ将它们作为新数组或其他类型的集合进行获取:

int[] arr = foo.A.ToArray();

为什么不将A公开为IReadOnlyList的实现

class Foo
{
    public IReadOnlyList<int> A { get { return a; } }
    private int[] a;
}

这使您可以将数组作为一个集合返回,他们可以在其中使用索引,但不能更改数组本身的内容。

听起来您需要索引器

...
public int this[int i]{
  get{return a[i];}
  set{a[i] = value;}
}
....

https://msdn.microsoft.com/en-us/library/6x16t2tx.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM