C # Call override method in superclass

Hey there. I just took C # to learn game programming using XNA, but I also have some experience with Java.

Here is my code essentially:

public class A
{
    public Rectangle getRectangle()
    {
        return [some rectangle];
    }

    public bool collision(A other)
    {
        Rectangle rect1 = getRectangle();
        Rectangle rect2 = other.getRectangle();
        return rect1.Intersects(rect2);
    }
}

public class B : A
{
    public Rectangle getRectangle()
    {
        return [some other rectangle];
    }
}

The problem occurs when I try to do something like this:

A a;
B b;
if(a.collision(b))
    ...

Where the B-version of the get rectangle is never really called, as far as I can tell. I tried a solution similar to the one suggested here but the message I get is basically "B.getRectangle () hides the inherited A.getRectangle () element. Use a new keyword if it was intended."

, . , java , # . , - , # java # , .

.

+3
4

Java, # . , , getRectangle: new .

virtual :

public virtual Rectangle getRectangle() { ... }

override :

public override Rectangle getRectangle() { ... }
+6

override getRectangle B :

public override Rectangle getRectangle()
+1

I don't know Java, but I assume they have some kind of virtual / override syntax for methods?

  public class A
  {
    virtual public Rectangle getRectangle()
    {
      return [some rectangle];
    }

    public bool collision(A other)
    {
      Rectangle rect1 = getRectangle();
      Rectangle rect2 = other.getRectangle();
      return rect1.Intersects(rect2);
    }
  }

  public class B : A
  {
     override public Rectangle getRectangle()
     { 
        return [some other rectangle];
     }
   }
0
source

I would suggest using Override to change getRectangle () functionality in B.

0
source

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


All Articles