简体   繁体   中英

My array class in C#

I'm trying to do this with Dictionary , Array seems more general so I'm using it as an example.

Class MyArray
{
    private Array array;

    public Array [p] // a property
    {
        get {return array[p]};
        set
        {
            array[p] = value;
            more_stuff();
        }
    }
}

This is sudo-code. I've included only a part of the class, where my problem would be. Can I use a property as above, or another structure to achieve this?

(new MyArray[]{4, 3, 1, 5})[2] = 4;

You're looking for an indexer .

So you're class should look like this:

class MyArray<T>
{
    private T[] array = new T[100];

    public T this[int p]
    {
        get 
        {
            return array[p];
        }
        set
        {
            array[p] = value;
            // more_stuff();
        }
    }
}

To be able to use a collection initializer (eg new MyArray<int>{4, 3, 1, 5} ), your class has to implement IEnumerable and provide a Add method.

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