[英]Why can't I use inherited objects in my inherited class?
class Vehicle // base class (parent)
{
public string brand = "Ford"; // Vehicle field
public void honk() // Vehicle method
{
Console.WriteLine("Tuut, tuut!");
}
}
class Car : Vehicle // derived class (child)
{
public string modelName = "Mustang"; // Car field
brand = "WHY İS NOT ??? "; // Error.
public void honk(); // Error.
}
Can't I do that?我不能那样做吗? Does the class we inherit have its functions, methods, and variables?
我们继承的class有它的函数、方法和变量吗? Did I learn something wrong?
我是不是学错了什么?
Note;笔记; It works within the main function.
它在主 function 内工作。
I've been dealing with this for a long time.我已经处理这个问题很长时间了。 : / (3+ hours)
: / (3+ 小时)
You can't just write to a field (defined in a base class) from the derived class like:您不能只从派生的 class 写入字段(在基类中定义),例如:
brand = "WHY İS NOT ??? "; // Error.
...because you aren't definining a new field, rather you are attempting to change brand
defined in the the base class Vehicle
. ...因为您没有定义新领域,而是试图更改基础 class
Vehicle
中定义的brand
。 Unfortunately the way it is written, the compiler thinks it's an orphaned assignment.不幸的是,它的编写方式,编译器认为这是一个孤立的赋值。 It should exist in a in a method or constructor .
它应该存在于方法或构造函数中。
Try placing it in a constructor:尝试将其放在构造函数中:
class Car : Vehicle // derived class (child)
{
public string modelName = "Mustang"; // Car field
public Car()
{
brand = "Acme";
}
public void honk() {}
}
public void honk(); // Error.
The problem here is that your method has no body.这里的问题是您的方法没有主体。 Whilst you can do that in an
interface
you can't in a non-abstract method belonging to a class.虽然您可以在
interface
中执行此操作,但您不能在属于 class 的非抽象方法中执行此操作。
Give it a minimal one like so:给它一个像这样的最小的:
public override void honk() { }
...or: ...或者:
public override void honk()
{
// same thing but formatted differently
}
Notice there is a new override
.注意有一个新的
override
。 If you want a new implementation of honk
in a derived class it's best to make the method virtual
.如果您想在派生的
honk
中实现 honk 的新实现,最好将方法设置为virtual
。
ie IE
class Vehicle // base class (parent)
{
// ...
public virtual void honk()
{
Console.WriteLine("Tuut, tuut!");
}
// ...
}
Alternatively you can use new
instead of override
but there are gotchas .或者,您可以使用
new
而不是override
但有陷阱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.