设置父类变量并将其放入子类c#

设置父类变量并将其放入子类c#,c#,oop,C#,Oop,我有一个家长级的动物和儿童级的狗 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) {

我有一个家长级的动物和儿童级的狗

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分? ..........................................
我只想在一侧设置变量,并在所有子类上设置simple时实现这一点。

您的代码将编译为:

new Animal().Height = 100;
new Dog().AnimalHeight();
如您所见,每次使用new关键字时,您都在创建一个新对象。你可以从这里开始阅读

所以你需要的是这样的东西:

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

var heights = dog.AnimalHeight(); 
abstract class Animal 
{
    public int Height { get; set; } // implement getter/setter-logc when needed
}
public class Dog : Animal
{
    public int AnimalHeight()
    {
        return this.Height;
    }
}

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

因为,您为对象动物指定了值100。然后创建一个新的对象狗。
在记忆中,动物和狗没有相同的分配,因此创建的两个对象的值不同。

实际上,这里有两个问题。最明显的是你在这里创建了两个完全不相关的对象——一个是
动物
类型,另一个是
类型。他们不共享任何成员,特别是他们完全独立

所以你应该只创造一只狗

//Executing the Code in Main Method
public static void main(stirng [] args){
    Dog dog = new Dog();
    dog.Height = 100;
    var heights = dog.AnimalHeight(); 
}
另一个相关但不太明显的问题更多的是设计问题:你的
Animal
-类应该是
abstract
。这样一来,您的问题就不会出现在第一位,因为您无法编写
newanimal()
。实际上,创造一种非特定类型的动物是没有意义的,而这正是
abstract
所做的

除此之外,通常不鼓励使用公共字段-至少对于非DTO类是这样。毕竟,您的代码应该如下所示:

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

var heights = dog.AnimalHeight(); 
abstract class Animal 
{
    public int Height { get; set; } // implement getter/setter-logc when needed
}
public class Dog : Animal
{
    public int AnimalHeight()
    {
        return this.Height;
    }
}

如果要共享所有动物实例的
高度
帐户,请将字段/属性设置为静态:

abstract class Animal 
{
    public static int Height { get; set; } 
}
现在,您可以在代码中的任何位置设置它:

Animal.Height = 10;
Dog d = new Dog();
Console.WriteLine(d.AnimalHeight()); // prints 10

每次使用
new
,您都在创建一个新对象。它不与以前创建的任何对象共享任何(非静态)数据。不要在Word中编写代码。此外,您还有两次
new
。你明白
new
的功能吗?创建基类
Animal
的实例毫无意义,IMHO。这就是抽象类的用途,所以要使动物抽象。你不能创建抽象类的实例,因为如果不指定动物实际上是什么样的动物,那么创建动物就毫无意义。因此,您必须在实例化时指定类型:
Animal dog=new dog()
@HimBromBeere我需要一个代码,在该代码中,我更改了侧边的高度,并且更改了所有child的值。。你明白吗?