首页 > 解决方案 > 设置父类变量并将其放入子类c#

问题描述

我有一个父类动物和子类狗。

Public Class Animal
{
    public int Height = 0;
}

Public Class Dog : Animal
{
    public int AnimalHeight()
    {
        return this.Height;
    }
}

//Executing the Code in Main Method
Public Static Void main(stirng [] args)
{
    Animal animal = new Animal();
    animal.Height = 100;

    Dog dog = new Dog();
    var heights = dog.AnimalHeight(); // why I didn't get 100 in this variable????
}

您可以看到我在父级中分配了 100 高度,为什么我在这个变量“高度”中没有得到 100?.............................................我只是想实现这一点,当我在一侧设置变量,并在所有子类上设置简单。

标签: c#oop

解决方案


您的代码将编译为此:

new Animal().Height = 100;
new Dog().AnimalHeight();

如您所见,每次使用 new 关键字时,您都在创建一个新对象。你可以在这里开始阅读https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types

所以你需要的是这样的:

Dog dog = new Dog();
dog.Height = 100;

var heights = dog.AnimalHeight(); 

话虽如此,我认为您根本不需要基类!


推荐阅读