c# - 重写属性 setter

标签 c# properties overriding

我正在制作一个程序,其中有一些球在弹跳,但现在我想继承该类并使新的类无法设置其速度

我已经尝试过这个,但没有任何作用

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/

相关文章:

c# - 带可选 ClientCertificate 的 SslStream AuthenticateAsServer

c# - 慢速图片框

c# - 在 C#(.Net Compact Framework)中完全加载我的表单时的通知?

java - 将 String ArrayList 添加到属性文件 java?

Android ListView : overriding causes scrolling do not executed

c# - Asp.net mvc fileupload 通过 ajax

java - 处理超出需要的属性

iphone - EXC_BAD_ACCESS 与 Objective-C 属性

django - 在 Django 模型中,如何防止基于特定字段的删除?

java - 多态性而不是覆盖方法,添加