正文

关键字集合和IDictionary 2007-08-26 11:02:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/edwardguo/28848.html

分享到:

关键字集合和IDictionary 
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);
        }
    }
_____________________________________________________________________________________________________
    public class Cow : Animal
    {
        public void Milk()
        {
            Console.WriteLine("{0} has been milked.", name);
        }
        public Cow(string newName)
            : base(newName)
        {
        }
    }
_____________________________________________________________________________________________________
    public class Chicken : Animal
    {
        public void LayEgg()
        {
            Console.WriteLine("{0} has laid an egg.", name);
        }
        public Chicken(string newName) : base(newName)
        {
        }
    }
_____________________________________________________________________________________________________
    public class Animals : DictionaryBase
    {
        public void Add(string newID, Animal newAnimal)
        {
            Dictionary.Add(newID, newAnimal);
        }
        public void Remove(string animalID)
        {
            Dictionary.Remove(animalID);
        }
        public Animals()
        {
        }
        public Animal this[string animalID]
        {
            get
            {
                return (Animal)Dictionary[animalID];
            }
            set
            {
                Dictionary[animalID] = value;
            }
        }
    }
_____________________________________________________________________________________________________
    public class Program
    {
        static void Main(string[] args)
        {
            Animals animalCollection = new Animals();
            Animal cow = new Cow("a");
            Animal chicken = new Chicken("b");
            animalCollection.Add("a", cow);
            animalCollection.Add("b", chicken);
            foreach (DictionaryEntry myEntry in animalCollection)
            {
                Console.WriteLine("New {0} object added to custon collection," +
                    "Name = {1}", myEntry.Value.ToString(), ((Animal)myEntry.Value).Name);
            }
            Console.ReadKey();
        }
    }

阅读(3877) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册