C#泛型学习2

今天学习了C#入门经典《Beginning Visual C# 2010》中泛型Ch12EX04,下面将Farm.cs的代码贴出,并对其中新的知识稍作总结:

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

namespace ConsoleApplication1
{
    public class Farm:IEnumerable 
        where T:Animal
    {
        private List animals = new List();
        public List Animals
        {
            get
            {
                return animals;
            }
            set
            {
                animals = value;
            
            }
        }
        public IEnumerator GetEnumerator()
        {
            return animals.GetEnumerator();    
        
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return animals.GetEnumerator(); 
        }
        public void MakeNoise()
        {
            foreach (T animal in animals)
            {
                animal.MakeANoise();
            }
        }
        public void FeedTheAnimals()
        {
            foreach (T animal in animals)
            {
                animal.Feed();
            }
        }
        public Farm GetCows()
        {
            Farm cowFarm = new Farm();
            foreach(T animal in animals)
            {
                if (animal is Cow)
                {
                    cowFarm.Animals.Add(animal as Cow);
                }
            }
            return cowFarm;
        }
    }
}
1、使用了IEnumberable接口的迭代器操作,所以包含了

using System.Collections;
在foreach循环中迭代器集合CollectionObject的执行过程如下:

(1)、调用collectionObject.GetEnumerator(),返回一个IEnumerator引用。这个方法可以通过IEnumerator接口的实现代码获得。

(2)、调用所返回的IEnumerator接口的MoveNext()方法。

(3)、如果MoveNext()方法返回true,就使用IEnumerator接口的Current属性获取对象的一个引用,用于foreach的循环。

(4)、重复(2)、(3)直到MoveNext()方法返回false为止,此时循环停止。

在foreach中跳出或者读取里面的变量,需要使用关键字yield对foreach循环暂停

(1)、yield break;//跳出foreach

(2)、yield return value;//返回foreach的过程量value

2、使用泛型定义了Fram类

public class Farm:IEnumerable 
        where T:Animal
该语句实现了两个功能

(1)、为Fram类创建了一个IEnumerable的接口

(2)、where T:Animal限制了T是Animal的继承类,该限制只能是范围逐渐缩小的方式,否则限制失效。

你可能感兴趣的:(C#,c#)