c# - 设置父类变量并将其放入子类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?.............................................我只是想实现这一点,当我在一侧设置变量,并在所有子类上设置简单。
解决方案
您的代码将编译为此:
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();
话虽如此,我认为您根本不需要基类!
推荐阅读
- c# - EntityException - 底层提供程序在打开时失败
- javascript - 在搜索组件 React、Semantic-UI-React 中渲染搜索结果的问题
- javascript - 如何在浏览器(react 或 vanilla js)中实现滚动劫持(scrolljacking)?
- c - 试图将数组中的数据保存到文件中
- android - 如何使用 Dagger2 提供 GoogleSignInOptions?
- excel - 为什么我突然收到“编译错误:需要常量表达式”?
- java - 如何使用 Jackson 以不区分大小写的方式从 Json 对象反序列化为 Boolean.class?
- unity3d - 在 Unity 中,我怎样才能得到一个 2d 多边形对撞机,它是一个大对撞机的面积减去大对撞机内的一些较小的对撞机?
- recaptcha-v3 - Google Reaptcha v3 仍然让垃圾邮件通过
- amp-html - 通过将我的页面重写为 AMP 可以获得什么好处?