我不明白参数如何在这个多态性代码中工作

时间:2012-06-14 08:20:27

标签: c# polymorphism

我哥哥为我编写了这段代码,展示了多态性的一个例子。但是从参数开始,我真的不明白它是如何工作的。有人可以剖析代码并告诉我一些代码如何一起工作以及它是如何工作的?

编辑:这是一个具体问题:哺乳动物。添加(新猫(“白雪公主”,“1”,“白色”,“蓝色”));这些数字有什么作用?他们的目的是什么以及他们如何使用代码?

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            List<Mammal> mammals = new List<Mammal>();

            mammals.Add(new Cat("Snow white", 1, 0, "White", "blue"));
            mammals.Add(new HumanFemale("Krysten", 72, 15, "White", "Blue"));
            mammals.Add(new Cat("Larry", 7, 2, "Orange", "Hazel"));
            mammals.Add(new Dog("Walt", 3, 5, "Brown", "Hazel"));
            mammals.Add(new HumanMale("Ryan", 72, 31, "White", "Blue"));
            mammals.Add(new Cat("Blacky", 5, 10, "Black", "Brown"));

            foreach (Mammal m in mammals)
            {
                m.Speak();
                m.Walk();
            }
            Console.ReadKey();
        }
    } // end of Program class declaration




    public abstract class Mammal
    {
        public Mammal(string name, int heightInInches, int age, string color, string eyeColor)
        {
            this.Name = name;
            this.HeightInInches = heightInInches;
            this.Age = age;
            this.Color = color;
            this.EyeColor = eyeColor;
        }

        private int _HeightInInches;
        private int _Age;

        /// <summary>
        /// Gets or sets the age (in years).
        /// </summary>
        public int Age
        {
            get 
            { 
                return _Age; 
            }
            set 
            {
                if (value < 0)
                {
                    throw new Exception("Invalid Age!");
                }
                _Age = value; 
            }
        }

        /// <summary>
        /// Gets or sets the height.
        /// </summary>
        public int HeightInInches
        {
            get 
            { 
                return _HeightInInches; 
            }
            set 
            {
                if (value < 0)
                {
                    throw new Exception("Invalid height!");
                }
                _HeightInInches = value; 

            }
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the skin or fur color.
        /// </summary>
        public string Color { get; set; }


        /// <summary>
        /// Gets or sets the eye color.
        /// </summary>
        public string EyeColor { get; set; }


        /// <summary>
        /// Causes the mammal to speak.
        /// </summary>
        public virtual void Speak()
        {
            Console.WriteLine("The mammal spoke.");
        }

        /// <summary>
        /// Causes the mammal to walk.
        /// </summary>
        public virtual void Walk()
        {
            Console.WriteLine("The mammal is walking.");
        }

    } // end of Mammal class declaration


    public class Dog : Mammal
    {
        public Dog(string name, int heightInInches, int age, string color, string eyeColor) 
            : base (name, heightInInches, age, color, eyeColor)
        {
        }

        public override void Speak()
        {
            Console.WriteLine("{0} the Dog says: 'Ruff!'", this.Name);
        }

        public override void Walk()
        {
            if (this.Age == 0)
            {
                Console.WriteLine("{0}, the {1} newborn puppy was just born and is too little to walk yet!", this.Name, this.Color);
            }

            else if (Age > 0 && Age <= 5)
            {
                Console.WriteLine("{0}, the {1} puppy is {2} years old and is running around like a hyper puppy, chewing up all the furniture. Oh nooo!", this.Name, this.Color, this.Age);
            }

            else if (Age > 5 && Age <= 10)
            {
                Console.WriteLine("{0}, the {1} dog is {2} years old and walks conservatively", this.Name, this.Color, this.Age);
            }

            else if (Age > 10)
            {
                Console.WriteLine("{0}, the {1} dog is {2} years old and walks very slowly, and has arthiritus in the joints.", this.Name, this.Color, this.Age);
            }
        }

    } // end of Dog class


    public class Cat : Mammal
    {
        public Cat(string name, int heightInInches, int age, string color, string eyeColor)
            : base(name, heightInInches, age, color, eyeColor)
        {
        }

        public override void Speak()
        {
            Console.WriteLine("{0} the Cat says: 'Meow!'", this.Name);
        }

        public override void Walk()
        {

            if (this.Age == 0)
            {
                Console.WriteLine("{0}, the {1} newborn Kitten was just born and is too little to walk yet!", this.Name, this.Color);
            }

            else if (Age > 0 && Age <= 5)
            {
                Console.WriteLine("{0}, the {1} Kitten is {2} years old and is running around like a hyper kitten!", this.Name, this.Color, this.Age);
            }

            else if (Age > 5 && Age <= 10)
            {
                Console.WriteLine("{0}, the {1} cat is {2} years old and walks conservatively", this.Name, this.Color, this.Age);
            }

            else if (Age > 10)
            {
                Console.WriteLine("{0}, the {1} cat is {2} years old and walks very slowly", this.Name, this.Color, this.Age);
            }
        }
    } // end of Cat class

    public abstract class Human : Mammal
    {
        public Human(string name, int heightInInches, int age, string color, string eyeColor)
            : base(name, heightInInches, age, color, eyeColor)
        {
        }


        public override void Walk()
        {

            if (this.Age == 0)
            {
                Console.WriteLine("{0}, the {1} newborn baby was just born and is too little to walk yet!", this.Name, this.Color);
            }

            else if (Age > 0 && Age <= 2)
            {
                Console.WriteLine("{0}, the {1} toddler is {2} years old and is crawling around!", this.Name, this.Color, this.Age);
            }

            else if (Age > 2 && Age <= 5)
            {
                Console.WriteLine("{0}, the {1} kid is {2} years old and is walking around!", this.Name, this.Color, this.Age);
            }

            else if (Age > 5 && Age <= 12)
            {
                Console.WriteLine("{0}, the {1} kid is {2} years old and walks briskly", this.Name, this.Color, this.Age);
            }

            else if (Age > 12 && Age <= 19)
            {
                Console.WriteLine("{0}, the {1} audlt is {2} years old and walks briskly", this.Name, this.Color, this.Age);
            }

            else if (Age > 20 && Age <= 60)
            {
                Console.WriteLine("{0}, the {1} adult is {2} years old and walks conservatively", this.Name, this.Color, this.Age);
            }

            else if (Age > 60)
            {
                Console.WriteLine("{0}, the {1} old person is {2} years old and walks with a cane", this.Name, this.Color, this.Age);
            }
        }

        public  override void Speak()
        {
            Console.WriteLine("The human spoke");
        }
    } // end of Human class

    public class HumanMale : Human
    {
        public HumanMale(string name, int heightInInches, int age, string color, string eyeColor)
            : base(name, heightInInches, age, color, eyeColor)
        {

        }

        public override void Speak()
        {
            if (this.Age == 0)
            {
                Console.WriteLine("{0}, the newborn baby boy was just born and is too young to speak", this.Name);
            }
            if (this.Age > 0 && this.Age <= 3)
            {
                Console.WriteLine("{0}, the toddler boy babbles 'goo goo ga ga'", this.Name);
            }

            if (this.Age > 3 && this.Age <= 5)
            {
                Console.WriteLine("{0}, the toddler boy says, 'I like fire trucks'", this.Name);
            }

            if (this.Age > 5 && this.Age <= 12)
            {
                Console.WriteLine("{0}, the young boy says: I want to be a fireman'", this.Name);
            }

            if (this.Age > 12 && this.Age <= 20)
            {
                Console.WriteLine("{0}, the teenage boy says: I want a girlfriend'", this.Name);
            }

            if (this.Age > 20)
            {
                Console.WriteLine("{0}, the adult male says, 'Hey hey hey!'", this.Name);
            }

        }

    } // end of HumanMale class

    public class HumanFemale : Human
    {
        public HumanFemale(string name, int heightInInches, int age, string color, string eyeColor)
            : base(name, heightInInches, age, color, eyeColor)
        {

        }

        public override void Speak()
        {
            if (this.Age == 0)
            {
                Console.WriteLine("{0}, the newborn baby girl was just born and is too young to speak", this.Name);
            }
            if (this.Age > 0 && this.Age <= 3)
            {
                Console.WriteLine("{0}, the toddler girl babbles 'da da goo goo ga ga'", this.Name);
            }

            if (this.Age > 3 && this.Age <= 5)
            {
                Console.WriteLine("{0}, the girl says 'I wanna be a princess'", this.Name);
            }

            if (this.Age > 5 && this.Age <= 12)
            {
                Console.WriteLine("{0}, the young girl says: I AM a princess'", this.Name);
            }

            if (this.Age > 12 && this.Age <= 20)
            {
                Console.WriteLine("{0}, the teenage girl says: Like, totally. Did you see that other chick? Like, what was she wearing'", this.Name);
            }

            if (this.Age > 20)
            {
                Console.WriteLine("{0}, the adult female says, 'Yep, I'm a woman.'", this.Name);
            }

        }

    } // end of HumanFemale class


} // end of namespace declaration

4 个答案:

答案 0 :(得分:1)

Mamal是所有狗,猫,人类,人类的一般类型。它们都有一些共同的属性和功能。

public Mammal(string name,int heightInInches,int age,string color,string eyeColor)

这一行是mamal类的构造函数。所有哺乳动物的属性名称,身高,年龄,颜色,眼睛颜色都很常见。

所有哺乳动物都可以行走(具有相同的功能),但都以不同的方式行走。所以我们需要覆盖这个功能,为不同的哺乳动物提供所需的功能。

public override void Walk() 这一行是步行功能被覆盖的方式。

哺乳动物类是抽象的。这意味着没有一种叫哺乳动物的动物。它只是一个广泛的定义。

希望它有所帮助。

答案 1 :(得分:1)

因此, Mamal 是您的基类,它将包含每个动物的所有常用属性。

然后你为你的动物(猫,狗)等派生类,这样它们将继承与基础相同的属性。

基础使用虚拟方法,因此您可以覆盖在派生类中的功能。

答案 2 :(得分:1)

对于编辑中的具体问题:

mammals.Add(new Cat("Snow white", 1, 0, "White", "blue")); 

该行可以改写为:

Cat aCat = new Cat("Snow white", 1, 0, "White", "blue"); 
mammals.Add(aCat);

在第一行中,您正在调用Cat的构造函数:

public Cat(string name, int heightInInches, int age, string color, string eyeColor)
            : base(name, heightInInches, age, color, eyeColor)

将“白雪公主”作为名称,将1作为heightInInches,将0作为年龄,将“白色”作为颜色,将“蓝色”作为eyeColor。构造函数是空的(它什么也没做,但是它基于Mammal构造函数(这是base(name, heightInInches, age, color, eyeColor)的含义),它被称为传递相同的参数。这意味着public Mammal(string name, int heightInInches, int age, string color, string eyeColor)被执行,所以最后得到一个Cat实例,其中所有属性都具有作为参数传递的值。

现在执行

 mammals.Add(aCat);

在这里,您要将Cat的实例添加到Mammal列表中。你这样做是因为Add期望哺乳动物作为参数,aCat是哺乳动物,因为它的类来自哺乳动物。

答案 3 :(得分:0)

基本上你的兄弟试图告诉你的是,当你从父类派生类时,你可以使用不同的,通常更复杂的方式来使用父类中的所有字段和属性。这就是多态意味着什么。

使用这些参数,你的兄弟就这样做了,因此每个派生自Mammal的类都采用相同的参数:名称,身高,年龄,颜色和眼睛颜色。在Mammal类中,然后他创建了它,以便每个参数设置其各自的属性,即如果您传入"Bob"作为名称参数,Name的{​​{1}}是然后鲍勃。当涉及到所有其他类时,他只是使用Mammal构造函数来使哺乳动物的初始化方式与base()相同。

你的兄弟然后进入了方法,这是实际做的。他制作了Mammal,这允许多态性。基本上,这表示任何子类都可以“virtual”或改变自己的方法。通过重写一个方法,子类说“当你在我身上使用这个方法时,就这样做,而不是我的父类如何做到这一点。”他通过重写每个子类中的方法,然后使用每个子类调用(或执行)方法来演示这一点。因为这些方法被覆盖了,所以对于猫而言,你会得到“喵喵”的声音,而对于一只狗而言,你会得到“咆哮”而不是“哺乳动物说话”。

另请注意,由于子类派生自override类,因此它们具有相同的属性,因此每个Mammal都具有可以使用的年龄,高度等。你的兄弟在方法中使用它来定制它们。

这是很多信息,但我希望这是可以理解的。