I have a class with a subclass. The superclass has a Position
property. The subclass must perform an additional operation when the Position
property is changed, so I am attempting to override the setter method and call the superclass' setter.
I think I've got the superclass setter calling part down, but I can't figure out how the overriding syntax works here.
Here is my best attempt:
The getter is there just for proof of concept -- suppose I wanted to override that too?
The getter and setter give me errors of this form:
cannot override inherited member 'superClassName.Position.[gs]et' because it is not marked virtual, abstract, or override
Here's a screencap of the errors too for good measure:
I also tried using the override keyword in front of the set
. Removing the superfluous getter has no effect.
What is the correct syntax?
The override is fine. However, as the error message states, you need to mark the property in the base class as virtual to be able to override it:
public virtual Vector2 Position
Unlike Java, class members are not virtual by default in C#. If you can't change the base class, you're out of luck.
Your Position
property isn't virtual in the base class, so you can't override it. If you make it virtual, you should be able to override it.
It gets a bit messy overriding one bit without the other - it's not the kind of thing I do very often, so I'd have to play around with it to make sure of what's going on, but the first thing to do would be to change the base class property...
This is also exactly what the compiler message is telling you:
cannot override inherited member 'superClassName.Position.[gs]et' because it is not marked virtual, abstract, or override
It's telling you something about the base class property - so that's what you need to change in order to override it. Compiler messages are there to help - pay close attention to them!
在您的基类中:添加关键字virtual
The problem is pointed out to you in the error message :)
You cannot override members that aren't virtual (or abstract) in the first place.
Your superclass needs to have virtual
in the property definition:
public virtual Vector2 Position { ... }
You cannot override members not marked as virtual
or abstract
Mark your Vector2
property in a super class as virtual
.
public virtual Vector2 Position
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.