C#数组添加元素

一、向数组添加元素

在C#中,只能在动态数组ArrayList类中向数组添加元素。因为动态数组是一个可以改变数组长度和元素个数的数据类型。

示例:
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections; // 导入命名空间

namespace Test
{
    class Program
    {
        // 为Program类定义一个静态方法Show
        public static void Show(ArrayList alist)
        {
            for (int i = 0; i < alist.Count; i++)
            {
                Console.Write("[{0}]:{1} ", i, alist[i]);
            }
            Console.WriteLine("\n");
        }
        static void Main(string[] args)
        {
            // C#数组添加元素-www.baike369.com
            ArrayList arraylist = new ArrayList();
            for (int i = 0; i < 7; i++)
            {
                arraylist.Add(i);
            }
            Console.WriteLine("1. 数组列表的容量为{0},实际包含{1}个元素:", 
                arraylist.Capacity, arraylist.Count);
            Show(arraylist);
            arraylist.Insert(3, 7); // 添加数组元素
            arraylist.AddRange(new int[] { 8, 9, 10 });// 在ArrayList末尾添加元素
            Console.WriteLine("2. 数组列表的容量为{0},实际包含{1}个元素:", 
                arraylist.Capacity, arraylist.Count);
            Show(arraylist);
            Console.ReadLine();
        }
    }
}

运行结果:
 
1. 数组列表的容量为8,实际包含7个元素:
[0]:0 [1]:1 [2]:2 [3]:3 [4]:4 [5]:5 [6]:6
 
2. 数组列表的容量为16,实际包含11个元素:
[0]:0 [1]:1 [2]:2 [3]:7 [4]:3 [5]:4 [6]:5 [7]:6 [8]:8 [9]:9 [10]:10

 

posted @ 2015-01-22 14:56  melao2006  阅读(47951)  评论(0编辑  收藏  举报