开发者

Building an object with a [] interface ( not from ILIst) in c#

I want to pass around some values in an array that will always be a known size. I would like to define a class that represents this array of decimal values which could not be resized, would always have the same number of elements, and supports the [] array notation.

In c++ I could do an operator overloading for this - but I can开发者_StackOverflow中文版't see how to do it in c#

To be clear - the use of the class would be something like:

MyValues values = new MyValues;
values[3] = 14;
values[7] = 10

.... And later

decimal aValue = values[2];

Suggestions?


You need to write an indexer, like this:

public decimal this[int index] {
    get { return data[index]; }
    set { data[index] = value; }
}


Use an indexer

public class MyValues {
    private readonly decimal[] numbers = new decimal[10];

    public decimal this[int index] {
        get { return numbers[index]; }
        set { numbers[index] = value; }
    }
}

You might want to add some bounds checking to provide better failiure messages. Also you probably do not want to hard code the array size.


Using an indexer, you could write a simple generic class like:

    public class FixedArray<T>
    {
        private T[] array;

        public int Length { get { return array.Length; } }

        public FixedArray (int size)
        {
            array = new T[size];
        }

        public T this[int index]
        {
            get { return array[index]; }
            set { array[index] = value; }
        }
    }


something like:

decimal this[int ind]
{
   get
   {
      return array[ind];
   }
   set
   {
      array[ind] = value;
   }
}


Try ReadOnlyCollection class. Also be aware of the dangers of arrays, really good article here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜