0

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

编辑:这是一个具体的问题:mamams.Add(new Cat("Snow white", 1, 0, "White", "blue")); 数字有什么作用?他们的目的是什么以及他们如何使用代码?

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

4 回答 4

1

哺乳动物是所有狗、猫、人类雌性、人类雄性的总称。它们都有一些共同的特性和功能。

公共哺乳动物(字符串名称,int heightInInches,int age,字符串颜色,字符串 eyeColor)

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

所有哺乳动物都可以行走(具有相同的功能),但都以不同的方式行走。因此我们需要重写此功能,以便为不同的哺乳动物提供所需的功能。

public override void Walk() 这一行是如何覆盖步行功能的。

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

希望能帮助到你。

于 2012-06-14T08:29:39.303 回答
1

因此,Mamal是您的基类,它将包含每个Animals的所有公共属性。

然后,您为您的动物(猫、狗)等派生类,因此这些将继承与基础相同的属性。

基类使用虚拟方法,以便您可以在派生类中覆盖它们的功能。

于 2012-06-14T08:31:06.490 回答
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)

传递“Snow white”作为名称,1 作为 heightInInches,0 作为年龄,“White”作为颜色,“blue”作为 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 期望一个 Mammal 作为参数,而 aCat 是一个 Mammal,因为它的类是从 Mammal 派生的。

于 2012-06-14T08:43:51.770 回答
0

基本上,您的兄弟试图向您展示的是,当您从父类派生类时,您可以以不同的并且通常更复杂的方式使用父类的所有字段和属性。这就是多态性的意思。

使用这些参数,您的兄弟做到了,因此派生自Mammal的每个类都采用相同的参数:姓名、身高、年龄、颜色和眼睛颜色。然后在Mammal类中,他使每个参数设置其各自的属性,即,如果您"Bob"作为名称参数传入NameMammal则为 Bob。当涉及到所有其他类时,他只是使用base()构造函数使哺乳动物以与Mammal.

然后你的兄弟进入了方法,这是实际在做什么。他制作了它们virtual,它允许多态性。基本上,这表示任何子类都可以“ override”或更改自己的方法。通过覆盖一个方法,子类说“当你在我身上使用这个方法时,用这种方法而不是我的父类是怎么做的。” 他通过覆盖每个子类中的方法,然后使用每个子类调用(或执行)方法来证明这一点。因为这些方法被覆盖,你会得到猫的“喵”或狗的“ruff”而不是“哺乳动物的辐条”。

Also note that since the child class derive from the Mammal class, they have the same properties, so every Mammal has an age, height, etc that it can use. Your brother used this in the methods to customize them.

It's a lot of info, but I hope it's understandable.

于 2012-06-14T08:51:55.267 回答