开发者

C# Dynamic size indexers

How to set up indexer that are dynamically grown in size ?Down开发者_JS百科,i used the fixed size array. If i use List<Employee> ,then there is no point to have indexers.so how can i keep the array to grow dynamically?

class Department
{
    private Employee[] employee = new Employee[6];

    public Employee this[int arg]
    {
        get { return this.employee[arg]; }
        set { this.employee[arg] = value; }
    }
}


You'd have to create a new array if the index is bigger than the current size, and copy the existing contents into the new array. Array.Resize will do this for you. (Note that it doesn't change the existing array - it returns you a new array of the specified size, containing the previous elements.)

You may want to consider resizing to a larger array than you really need, just so that you don't have to resize as often.

Are you sure it wouldn't be easier just to use a List<T> though? Doing this sort of thing manually is rather tedious when it's built into the framework already...


If i use List ,then there is no point to have indexers

Why? You can still using indexes with lists, and you can define the initial capacity of the list at construction time. See here: http://msdn.microsoft.com/en-us/library/d0cyc8ex.aspx

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜