简体   繁体   English

了解如何使用类

[英]Understanding how to use classes

I am trying to understand how to use or access multiple classes in C#, can someone explain to me what this code does? 我试图了解如何在C#中使用或访问多个类,有人可以向我解释这段代码的作用吗?

public class Mammal : Animal
{   
    public Mammal(String name) : base(name) { }

    public override void Eat(Food food)
    {
        Console.WriteLine("Mammal \"" + Name + "\" eats " + food.Name);
    }
}

What is the purpose of public override void Eat(Food food) ? public override void Eat(Food food)的目的是什么? I mean what does it do?? 我的意思是它做了什么?

namespace ConsoleApplication1
{
    public class Food
    {
        private String name;

        Food(String name)
        {
            this.name = name;
        }

        public String Name
        {
            get 
            {
                return name;
            }
            set
            {
                name = value;
            }
        }   
    }

    public class Animal
    {
        private String name = "no name";

        public String Name {
            get 
            { 
                return name; 
            }
            set 
            { 
                name = value; 
            }
        }

        private Animal() { }

        public Animal(String name)
        {
            this.name = name;
        }

        public virtual void Eat(Food food)
        {
            Console.WriteLine("Animal \"" + Name + "\" eats " + food.Name);
        }

        public virtual void Born() 
        {
            Console.WriteLine("Animal \"" + Name + "\" is born");
        }

        public virtual void Die() 
        {
            Console.WriteLine("Animal \"" + Name + "\" is died");
        }
    }

    public class Mammal : Animal
    {   
        public Mammal(String name) : base(name) { }

        public override void Eat(Food food)
        {
            Console.WriteLine("Mammal \"" + Name + "\" eats " + food.Name);
        }

        public override void Born()
        {
            Console.WriteLine("Mammal \"" + Name + "\" is born");
        }

        public override void Die()
        {
            Console.WriteLine("Mammal \"" + Name + "\" is died");
        }

        public virtual void FedMilk(Mammal[] children)
        {
            for (Int32 i = 0; i < children.Length; i++)
            {
                Console.WriteLine("Mammal \"" + Name + "\" feds milk child \"" + children[i].Name + "\"");
            }
        }
    }

    public class Horse : Mammal
    {
        public Horse(String name) : base(name) { }

        public override void Eat(Food food)
        {
            Console.WriteLine("Horse \"" + Name + "\" eats " + food.Name);
        }

        public override void Born()
        {
            Console.WriteLine("Horse \"" + Name + "\" is born");
        }
    }
}

Ok, 好,

You have defined a basic class called mammal and then you created different types of mammals like Animal and then a specific animal (Horse ). 你定义了一个叫哺乳动物的基本类,然后你创造了不同类型的哺乳动物,如动物,然后是特定的动物(马)。

So every mammal needs to eat, so that why you have created a functions called eat.. 所以每个哺乳动物都需要吃,所以你为什么要创造一个名为eat的功能。

But every animal which is a mammal eats the same things? 但是每一只哺乳动物都会吃同样的东西吗? NO!!! 没有!!!

But every mammal needs to eats . 但每个哺乳动物都需要吃。

So in that place the override attribute comes handy, it allows you to override the basic function of "eat" so you would be able to specified what eats every specific animal. 所以在那个地方,覆盖属性很方便,它允许你覆盖“吃”的基本功能,这样你就可以指定每个特定动物吃什么。

So when you create a dog class you will override the eat function and specified whom eat some dog food. 因此,当您创建一个狗类时,您将覆盖吃功能并指定谁吃一些狗食。

But because all of your specific animal are also animals you can refer to them as animals and print the eat function. 但是因为你所有的特定动物都是动物,你可以将它们称为动物并打印吃功能。

lets say you want to see what eats every animal. 让我们说你想看看每只动物吃什么。 you will create a loop of a list of animals and print the eat function. 你将创建一个动物列表循环并打印eat函数。

because you have override the eat function and specified every food. 因为你已经覆盖了吃功能并指定了每一种食物。 you will get the correct food for each animal. 你会得到每只动物的正确食物。

am i making my self clear? 我让自己清楚了吗?

for example see this code 例如,请参阅此代码

List<Animal> animals = new List<Animal>();

            Horse hr = new Horse();
            Dog dg = new Dog();
            Bird br = new Bird();

            animals.Add(hr);
            animals.Add(dg);
            animals.Add(br);

            foreach(var animal in Animals)
            {
                Console.WriteLine(animal.eat());
            }

override is a keyword in C# that says "Hey, I want to do this thing differently than my base (parent) class." override是C#中的一个关键字,表示“嘿,我想以不同于我的基础(父级)类来做这件事。” It has to do with polymorphism . 它与多态性有关

In the case of the code posted, you have a class hierarchy . 在发布代码的情况下,您有一个类层次结构 A Mammal is a specific type of Animal . Mammal是一种特定类型的Animal So we can say Mammal inherits from the Animal base class ( Mammal : Animal ). 所以我们可以说哺乳动物继承自动物基类Mammal : Animal )。

In the Animal base class, there are virtual members (like public virtual void Eat ). Animal基类中,有virtual成员(如public virtual void Eat )。 Any of these virtual members can be overridden in a more derived class. 可以在更派生的类中覆盖任何这些虚拟成员。

When you override a virtual property or method in a more derived class, you are saying "When someone uses this property or method, do it differently if the object is an instance of Mammal than you would if the instance was a basic Animal, or some other kind of Animal (such as a Bird, Fish, or Reptile)". 当您在更多派生类中override虚拟属性或方法时,您会说“当有人使用此属性或方法时,如果对象是Mammal的实例,则执行的操作与实例是基本Animal或者某些实例相同。其他种类的动物(如鸟类,鱼类或爬行动物)“。

Animal beaver = new Mammal("beaver"); // "Mammal beaver"
Animal finch = new Bird("finch"); // "Bird finch"
Animal japaneseHuman = new Mammal("Japanese human"); // "Mammal Japanese human"
Animal godzilla = new Reptile("godzilla"); // "Reptile godzilla"

beaver.Eat(new Food("wood")); // "eats wood"
finch.Eat(new Food("nuts")); // "eats nuts"
japaneseHuman.Eat(new Food("whale")); // "eats whale"
godzilla.Eat(new Food("Japanese people")); // "eats Japanese people"

You can also override types that are declared as abstract in an abstract base class. 您还可以override在抽象基类中声明为abstract的类型。 Overriding abstract works almost just like overriding virtual , except that there is no base implementation defined (only the base signature is defined). 覆盖abstract工作几乎就像覆盖virtual ,除了没有定义基本实现(只定义了基本签名 )。

The override provides the ability for a class to change how a specific method is implemented. 覆盖提供了类更改特定方法实现方式的能力。

From reading the sample code, all Animal s can be born, can die, and can eat food. 从阅读示例代码,所有Animal都可以出生,可以死,并可以吃食物。 The overrides in the Mammal and Horse classes allow for different functionality. MammalHorse类中的覆盖允许不同的功能。 The way a Horse eats can be different different to how a Dog eats. Horse吃的方式可能与Dog吃的方式不同。

The fact that the methods are virtual allow for ode such as : 方法是虚拟的事实允许颂歌,例如:

Animal[] animals = new Animal[] { new Horse(), new Dog(), new Mammal() };
foreach (Animal animal in animals)
{
    animal.Born();
    animal.Eat(new Food());
    animal.Die();
}

Each of the calls above flow down and will call the Horse.Born() or Dog.Eat(Food) implementations. 上面的每个调用都会向下流动并调用Horse.Born()Dog.Eat(Food)实现。

Blockquote what is the purpose of public override void Eat(Food food) i mean what does it do?? Blockquote什么是公共覆盖的目的void Eat(食物食品)我的意思是它做什么?

Mammals is a class of type Animal. 哺乳动物是一类动物。 Mammal will inherit all the properties and methods Animal has and must have implementations for everything that's abstract in Animal if Animal is an abstract class. 如果Animal是一个抽象类,Mammal将继承Animal所有的属性和方法,并且必须具有Animal中抽象的所有实现。 All abstract means is that it's merely a skeleton to force the subclasses to implement things the abstract class knows they must have in order to function properly. 所有抽象意味着它只是一个框架,它强制子类实现抽象类知道它们必须具有的东西才能正常运行。

Mammals has a method, Food, that is specific to its class and noted to be different than what all the other animals do. 哺乳动物有一种方法,食物,这是特定于它的类,并注意到与所有其他动物不同。 Even though all animals may have a method in the base class animal defined for food, mammals will always use its own method--that's what override means. 尽管所有动物都可能在为食物定义的基类动物中有一种方法,但哺乳动物将始终使用自己的方法 - 这就是覆盖意味着什么。

So to review: 所以要审查:

Mammal someMammal = new Mammal();
someMammal.Eat(new Food());

the version of eat that will be called is Mammal's Eat in this case. 在这种情况下,将被称为“哺乳动物”的食物的版本。

Now if we did this: 现在,如果我们这样做:

Animal someAnimal = new Animal();--must be non-abstract
someaAnimal.Eat(new Food());

here we call animal's version of Eat. 在这里我们称动物的版本为Eat。

Now what if we did this? 现在怎么做呢?

Mammal someMammal = new Mammal();
someMammal.Eat(new Food());--no surprise we get mammal's eat
Animal someAnimal = (Animal)someMammal;
someAnimal.Eat(new Food());--but what happens here!?

Well, because Mammal's eat is an override, the mammal eat method will be called again. 好吧,因为哺乳动物的吃是一种超越,哺乳动物吃的方法将被再次召唤。 Had it not been override, we would have gotten Animal's. 如果它没有被覆盖,我们就会得到动物的。

for reference, to learn more about override, base/derived classes, and virtual classes. 供参考,以了解有关覆盖,基类/派生类和虚拟类的更多信息。 http://msdn.microsoft.com/en-us/library/ms173152%28v=vs.80%29.aspx http://msdn.microsoft.com/en-us/library/ms173152%28v=vs.80%29.aspx

what is the purpose of public override void Eat(Food food) i mean what does it do?? 公共覆盖的目的是什么无效吃(食物食品)我的意思是它做什么?

In the base class, the Eat method has been marked as virtual. 在基类中,Eat方法已标记为虚拟。 This means that it can be reimplemented by any class that inherits it. 这意味着它可以由任何继承它的类重新实现。 That is what this bit of code does: 这就是这段代码的作用:

public override void Eat(Food food)

It defines the Eat method for the inheriting class. 它为继承类定义了Eat方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM