C# Array類的基本操作

iamzxf發表於2015-04-22

C#中Array類可以用於對陣列進行定義,與常規的定義方式不同,Array類定義的陣列可以從任意正整數開始,而不一定要從0開始。

一維陣列的例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArrayDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int []dim={5};
            int[]lowBound={2};
            Array myArray=Array.CreateInstance(typeof(int),dim, lowBound);

            for(int i=1;i<=5;i++)
            {
                myArray.SetValue(i,1+i);
            }

            for(int i=2; i<=6;i++)
                Console.WriteLine(myArray.GetValue(i));

            Console.ReadLine();
        }
    }
}


二維陣列的例子:

<span style="font-family:SimHei;font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace arrayDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Array intarray1=Array.CreateInstance(typeof(int), 5);
            for (int i = 0; i < 5;i++)
                intarray1.SetValue(20, i);

            for (int i = 0; i < 5; i++)
                Console.Write("{0,5}",intarray1.GetValue(i));

            Console.WriteLine();

            int[] lengths = { 2, 3 };
            int[] lowBounds = { 1, 10 };

            Array computerLanguage = Array.CreateInstance(typeof(string), lengths, lowBounds);
            for (int i = lowBounds[0]; i < lowBounds[0] + lengths[0]; i++)
                for (int j = lowBounds[1]; j < lowBounds[1] + lengths[1]; j++)
                    computerLanguage.SetValue("cLanguage", i, j);

            for (int i = lowBounds[0]; i < lowBounds[0] + lengths[0]; i++)
            {
                for (int j = lowBounds[1]; j < lowBounds[1] + lengths[1]; j++)
                    Console.Write("{0,10}",computerLanguage.GetValue(i, j));
                Console.WriteLine();
            }

           Console.ReadLine();
            
        }        
    }
}</span>



相關文章