我正在制作一个程序,其中有一些球在弹跳,但现在我想继承该类并使新的类无法设置其速度
我已经尝试过这个,但没有任何作用
public class Ball {
public Ball(double posX, double posY, double rad, Vector vel) {
Pos = new Point(posX, posY);
Rad = rad;
Vel = vel;
}
public double Rad { get; set; }
public Point Pos { get; set; }
public Vector Vel { get; set; }
}
public class StaticBall : Ball {
public StaticBall(double posX, double posY, double rad)
: base(posX, posY, rad, new Vector(0, 0)) {
}
public Vector Vel {
get { return Vel; }
set { Vel = Vel; }
}
}
我应该怎么做?
最佳答案
I'm making a program where there are some balls bouncing around, but now I want to inherit that class and make that new one impossible to set it's velocity
您的要求违反了Substitution Principle 。如果 Ball
的速度可以更改,则任何继承于 Ball
的类的速度也必须是可以更改的。
解决方案:不要从 Ball
继承 ConstantSpeedBall
,而是创建一个新的基类 BallBase
并继承 ConstantSpeedBall
和来自它的 ChangingVelocityBall
。
关于c# - 重写属性 setter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18161079/