C#日写点滴(4)

Array类:

   用括号声明数组是C#中使用Array类的记号。在后台使用C#的语法,会创建一个派生于抽象蕨类的Array的新类,这样,就可以使用Array类为每个C#数组定义的方法和属性了。如:Length属性、Rank属性、及foreach语句迭代数组。

   由于Array是一个抽象类,所以不能使用构造函数来创建数组。除了可以使用C#语法创建数组实例外,还可以全用静态方法CreateInstance()创建数组。如果事先不知道元素的类型,就可以使用该静态方法。

   CreateInstance()方法的第一个参数是元素的类型,第二个参数定义数组的大小 ,可以用SetValue()方法设置值,GetValue()方法读取值。

using System;
using Test;
using PersonInfo;
using System.Collections.Generic;
using System.Text;


namespace Test
{
    public class Class1
    {

        public static void Main()
        {
            Array intArray = Array.CreateInstance(typeof(int), 5);
            for (int i = 0; i < 5; i++)
            {
                intArray.SetValue(33, i);

            }
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(intArray.GetValue(i));
            }

            int[] lengths ={ 2, 3 };
            int[] lowerBounds ={ 1, 10 };
            Array racers=Array.CreateInstance(typeof(Person),lengths,lowerBounds);
            racers.SetValue(new Person("Alain","Prost"), 1, 10);
            racers.SetValue(new Person("Emerson", "fittipaldi"), 1, 11);
            racers.SetValue(new Person("Ayrton", "Senna"), 1, 12);
            racers.SetValue(new Person("Ralf", "Schumacher"), 2, 10);
            racers.SetValue(new Person("Fernando", "Alonso"), 2, 11);
            racers.SetValue(new Person("Jenson", "Button"), 2, 12);
            foreach (Person p in racers)
            {
                Console.WriteLine(p.ToString());
            }

        }

    }
}

namespace PersonInfo
{
    public class Person :object
    {
        public Person()
        {

        }

        public Person(string firstName, string lastName)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
        }

        public string FirstName ;//{ get; set; }


        public string LastName;// { get; set; }

        public override string ToString()
        {
            return String.Format("{0} {1}", FirstName, LastName);
        }
    }
  

}

Array类实现了对数组中的元素的冒泡排序。Sort()方法需要数组中的元素实现IComparable接口。如:System.Sting 、System.Int32实现了IComparable接口。所以可以对包含这些类型的数组进行排序。

猜你喜欢

转载自blog.csdn.net/cigogo/article/details/4213870