How to pass an object to call a method?

I have the following class hierarchy:

public class AI { public AI() { } public virtual void Update(float frameTime) { } } public class Boss : AI { public Boss() : base() { } public override void Update(float frameTime) { Console.WriteLine("Boss Update"); } } 

I have a Symbol that contains an AI variable that then stores a Boss instance and try to use it as such to get the Boss Update function, not the base class.

 AI ai = new Boss(); (Boss)ai.Update(0f); 

This does not work, but what is the correct method for doing this in C #? It worked correctly with another class of AI, where I didn’t even need to drop it at all, it just ran the correct version of Update, so I had to change something inadvertently.

+4
source share
3 answers

The operator has a higher priority than casting, so your code is interpreted as:

 (Boss)(ai.Update(frameTime)); 

You need to add an extra pair of parentheses to get what you want:

 ((Boss)ai).Update(frameTime); 

However, it is not necessary to perform this technique, since your method is virtual.

You can also consider changing the type of AI as an abstract class or (if possible) interface.

+18
source

You will need to add parsers around the actor and the cast object to call the method in the cast value (i.e. ((SomeType)someObj).SomeMethod() ), but this does not apply to the point, since casting is not required.

Update is virtual and the call is polymorphic, so although the ai variable has been declared as an ai instance, it will actually call Boss.Update() as the type that is really behind the scenes.

That is why polymorphism is powerful. You do not need to know that the main type needs to get the right implementation-specific behavior.

+4
source

What your line of code says:

 AI ai = new Boss(); (Boss)ai.Update(); 

accepts what is returned from Update(); , and throws it on the Boss type

what you need to do is

 AI ai = new Boss(); ((Boss)ai).Update(); 

which is different ai to print Boss and call the Update() method.

0
source

Source: https://habr.com/ru/post/1386418/


All Articles