简体   繁体   中英

Is there any better way to encapsulate an array?

How I do it currently:

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

I think it's bad because it creates a clone and casts whenever I access it. I know I can work around it by introducing an additional variable like this

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

but still it just looks bad.

I also dislike the java way of encapsulating

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

because I dont get the advantages of using an array.

Is there any better way to do this?

edit: I want an array of encapsulated variables. The problem is that

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

is not an array of encapsulated variables because I can modify elements of the array from outside of the class.

edit: It should also work with multidimensional arrays

Arrays implement IReadOnlyList<T> which exposes all of the relevant information you want (an iterator, an indexer, count, etc.) without exposing any of the mutable functionality of the array.

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

alternatively, you could use an iterator/generator to return the items as requested:

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

... then iterate over them normally or use LINQ to get them as a new array or other type of collection:

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

Why not expose A as a implementation of IReadOnlyList

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

This allows you to return the Array as a collection where they can use the index but cannot change the contents of the array itself.

sounds like you need an indexer

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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