C#學習筆記(集合)

來源:互聯網
上載者:User

標籤:

1 System.Array類和System.collections.ArrayList類

樣本:控制台程式,新疆三個類,抽象類別Animal以及兩個繼承類Cows和Chicken

Animal.cs

public abstract class Animal
{
  protected string name;

  public string Name
  {
    get { return name; }
    set { name = value; }
  }
  public Animal()
  {
    name = "The animal with no name";
  }
  public Animal(string newName)
  {
    name = newName;
  }
  public void Feed()
  {
    Console.WriteLine("{0} has been fed.", name);
  }
}

Cows.cs

public class Cow : Animal
{
  public void Milk()
  {
    Console.WriteLine("{0} has been fed.",name);
  }
  public Cow(string newName)
  : base(newName)
  {

  }
}

Chicken.cs

public class Chicken : Animal
{
  public void LayEgg()
  {
    Console.WriteLine("{0} has been fed.", name);
  }
  public Chicken(string newName)
  : base(newName)
  {

  }
}

Program.cs

class Program
{
  static void Main(string[] args)
  {
    Console.WriteLine("Create an Array type collection of Animal " + "object and use it");
    Animal[] animalArray = new Animal[2];
    Cow myCow1 = new Cow("Deirdre");
    animalArray[0] = myCow1;
    animalArray[1] = new Chicken("Ken");

    foreach (Animal myAnimal in animalArray)
    {
      Console.WriteLine("New {0} object added to Array collection," + "Name = {1}", myAnimal.ToString(), myAnimal.Name);
    }

    Console.WriteLine("Array collection contatains {0} objects.",animalArray.Length);

    animalArray[0].Feed();
    ((Chicken)animalArray[1]).LayEgg();
    Console.WriteLine();

    Console.WriteLine("Create an ArrayList type collection of Animal " + "object and use it");
    ArrayList animalArrayList = new ArrayList();
    Cow myCow2 = new Cow("Hayley");
    animalArrayList.Add(myCow2);
    animalArrayList.Add(new Chicken("Roy"));
    foreach(Animal myAnimal in animalArrayList)
    {
      Console.WriteLine("New {0} object added to ArrayList collection," + "Name = {1}",myAnimal.ToString(),myAnimal.Name);
    }
    Console.WriteLine("ArrayList collection contains {0} objects.",animalArrayList.Count);
    ((Animal)animalArrayList[0]).Feed();
    ((Chicken)animalArrayList[1]).Feed();
    Console.WriteLine();

    Console.WriteLine("Additional manipulaion of ArrayList:");
    animalArrayList.RemoveAt(0);
    ((Animal)animalArrayList[0]).Feed();
    animalArrayList.AddRange(animalArray);
    ((Chicken)animalArrayList[2]).LayEgg();
    Console.WriteLine("The animal called {0} is at index {1}.",myCow1.Name,animalArrayList.IndexOf(myCow1));
    myCow1.Name = "Janice";
    Console.WriteLine("The animal is called {0}.",((Animal)animalArrayList[1]).Name);
    Console.ReadKey();
  }
}

輸出結果:

 

  這個樣本建立了兩個對象集合,第一個使用System.Array類(這是一個簡單的數組),第二個集合使用了System.collections.ArrayList類。

  對於簡單的數組來說,只有用固定的大小初始化後,才能使用它。

  Animal[] animlaArray = new Animal[2];

  而ArrayList集合不需要初始化其大小,所以可以使用一下代碼建立列表animalArrayList;

  ArrayList[] myArrayList = new ArrayList();

  因為數組是參考型別,因此用一個長度初始化數組並沒有初始化他所包含的項。要使用一個指定的項,該項還需要初始化,即需要給這個項賦予初始化了的對象:

  Cow myCow1 = new Cow("Deirdre");

  animalArray[0] = myCow1;

  animalArray[1] = new Chicken("Ken");

  對於ArrayList集合,他沒有現成的項。他沒有null引用的項。這樣就不能以相同的方式給索引賦予新執行個體。我們是用ArrayList對象的add()方法加新項:

  Cow myCow2 = new Cow("hayley");

  animalArrayList.Add(myCow2);

  animalArrayList.Add(new Chicken("Roy"));

注意:

  數組的類型是抽象類別型Animal,因此不能直接調用由衍生類別提供的方法,而必須使用資料類型轉換:

  ((Chicken)animalArray[1]).LayEgg();

2 定義集合,建立自己的、強化類型的集合

2.1 System.Collections.CollectionBase類

執行個體:

在上面的基礎之上添加一個新類Animals.cs

Animals.cs

public class Animals : CollectionBase
{
  public void Add(Animal newAnimal)
  {
    List.Add(newAnimal);
  }
  public void Remove(Animal newAnimal)
  {
  List.Remove(newAnimal);
  }
  public Animals()
  {
    Console.WriteLine("This is Animals!!!");
  }
  public Animal this[int animalIndex]
  {
    get
    {
      return (Animal)List[animalIndex];
    }
    set
    {
      List[animalIndex] = value;
    }
  }
}

Program.cs

class Program
{
  static void Main(string[] args)
  {
    Animals animalCollection = new Animals();
    animalCollection.Add(new Cow("Jack"));
    animalCollection.Add(new Chicken("Vera"));
    foreach (Animal myAnimal in animalCollection)
    {
      myAnimal.Feed();
    }
    Console.ReadKey();
  }
}

輸出結果:

這個執行個體使用了上一節詳細介紹的代碼,實作類別Animal中強化類型的Animal對象集合。Main()中代碼僅執行個體化了一個Animals對象animalCollection,添加了兩個項,再使用foreach迴圈調用這個兩個對象繼承於基類Animal的Feed方法。

3 迭代器

  迭代器的定義是,他是一個代碼塊,按順序提供了要在foreach迴圈中使用的所有值。一般情況下,這個代碼塊是一個方法,但也可以使用訪問器和其他代碼塊作為迭代器。這裡為了簡單起見,介紹方法:

public static IEnumerable SimpleList()

{

  yield return "string 1";

  yield return "string 2";

  yield return "string 3";

}

public static void Main(string[] args)

{

  foreach(string item in SimpleList())

  {

    Console.WriteLine(item);

  }

  Console.ReadKey;

}

  實際上,並沒有返回string類型的項,而是返回了object類型的值。因為object是所有類型的基類,也就是說,可以從yield語句中返回任意類型。

 

C#學習筆記(集合)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.