Hey there. I just picked up C# to learn game programming with XNA, but I also have some experience in Java.
Here's my code, in essence:
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 arises when I try something like开发者_C百科 this:
A a;
B b;
if(a.collision(b))
...
Where B's version of get rectangle is never actually called, as far as I can tell. I tried a solution like the one suggested here but the message I get is basically "B.getRectangle() hides inherited member A.getRectangle(). Use the new keyword if this was intended."
I appreciate in advance any help I receive. I'm thinking my past java experience is getting in the way of understanding how C# is different. I guess if anyone just knows of a good link that explains the differences between C# and java or just how C# works in this respect that could suffice.
Cheers.
Unlike Java, methods in C# are not marked virtual by default. What your current code is doing is hiding the getRectangle
method: there is an implicit new
modifier on the declaration of the method in the derived class.
You need to explicitly include the virtual
modifier in the method-declaration in the base class:
public virtual Rectangle getRectangle() { ... }
and override
it in the derived class with:
public override Rectangle getRectangle() { ... }
You need to use the keyword override
for the getRectangle
method in class B like so:
public override Rectangle getRectangle()
I don't know Java, but I assume they have some sort 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];
}
}
I would suggest use Override to change the functionality of getRectangle() in B.
精彩评论