例子:以下的分别是一段java和对应的C#代码,在C#代码中如果不加上override,virutal 的话,就会产生不同结果,如果没有public的话,就会编译错误。
看似简单的代码要求掌握很多知识才能判断出其正确结果
两段代码的结果都是:
(0, 0)
(2.7182798, 3.14159)
(2, 3)
(2, 3)
Java中的代码:
//
//Test.java
//
class Point
{
int x = 0, y = 0;
void move(int dx, int dy) { x += dx; y += dy; }
int getX() { return x; }
int getY() { return y; }
int color;
}
class RealPoint extends Point
{
float x = 0.0f, y = 0.0f;
void move(int dx, int dy) { move((float)dx, (float)dy); }
void move(float dx, float dy) { x += dx; y += dy; }
int getX() { return (int)Math.floor(x); }
int getY() { return (int)Math.floor(y); }
}
class Test
{
public static void main(String[] args) {
RealPoint rp = new RealPoint();
Point p = rp;
rp.move(1.71828f, 4.14159f);
p.move(1, -1);
show(p.x, p.y);
show(rp.x, rp.y);
show(p.getX(), p.getY());
show(rp.getX(), rp.getY());
}
static void show(int x, int y)
{
System.out.println("(" + x + ", " + y + ")");
}
static void show(float x, float y) {
System.out.println("(" + x + ", " + y + ")");
}
}
改成C#代码是:
//
//Test.cs
//
public static void Main(String[] args)
{
RealPoint rp = new RealPoint();
Point p = rp;
rp.move(1.71828f, 4.14159f);
p.move(1, -1);
show(p.x, p.y);
show(rp.x, rp.y);
show(p.getX(), p.getY());
show(rp.getX(), rp.getY());
Console.Read ();
}
static void show(int x, int y)
{
System.Console.WriteLine ("(" + x + ", " + y + ")");
}
static void show(float x, float y)
{
System.Console.WriteLine("(" + x + ", " + y + ")");
}
}
class Point
{
public int x = 0, y = 0;
public virtual void move(int dx, int dy) { x += dx; y += dy; }
public virtual int getX() { return x; }
public virtual int getY() { return y; }
public int color;
}
class RealPoint: Point
{
public float x = 0.0f, y = 0.0f;
public override void move(int dx, int dy) { move((float)dx, (float)dy); }
public void move(float dx, float dy) { x += dx; y += dy; }
public override int getX() { return (int)Math.Floor(x); }
public override int getY() { return (int)Math.Floor(y); }
}