繁体   English   中英

抽象类和只读属性

[英]Abstract Classes and ReadOnly Properties

让我们上三个课;

Line
PoliLine
SuperPoliLine

对于所有这三个类别,都定义了Distance

但仅对于“ Line可以设置Distance

是否有可能建立一个通用的抽象 (MustInherit)类Segment ,将Distance作为(抽象+? ReadOnly )成员?

对于VB.NET的问题,但C#也欢迎您回答。


商业背景

想象一辆公共汽车。 它有很多StationMainStation和2 TerminalStation 因此, Line在2个工作站之间, PoliLine在2个MainStation之间, SuperPoliLine在2个TerminalStation之间。 所有“线”均为“段”,但只能定义两个站之间的距离A-> B- 线

您不能同时覆盖并重新声明(添加集合),但是您可以执行以下操作:

基类:

protected virtual int FooImpl { get; set; } // or abstract
public int Foo { get { return FooImpl; } }

派生类:

new public int Foo {
    get { return FooImpl; }
    set { FooImpl = value; }
}

// your implementation here... 
protected override FooImpl { get { ... } set { ... } }

现在,您还可以根据需要覆盖FooImpl。

由于您希望它在一个类中可设置但在其他类中不可设置,因此我通常不对“特殊”类(在此情况下为setter)使用属性。

public class Segment
{
    protected int _distance;
    public int Distance { get { return _distance; } }
}

public class Line : Segment
{
    public int SetDistance(int distance) { _distance = distance; }
}
public class Segment
{
    private int distance;
    public virtual int Distance
    {
        get { return distance; }
        set { distance = value; }
    }
}

public class Line : Segment
{
    public override int Distance
    {
        get { return base.Distance; }
        set
        {
            // do nothing
        }
    }
}

编辑版本:

    public abstract class Segment
    {            
        public abstract int Distance { get; set; }
    }

    public class Line : Segment
    {
        private int distance;
        public override int Distance
        {
            get { return distance; }
            set
            {
                // do nothing
            }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM