简体   繁体   English

抽象类和只读属性

[英]Abstract Classes and ReadOnly Properties

Let's have three classes; 让我们上三个课;

Line
PoliLine
SuperPoliLine

for all that three classes a Distance is defined. 对于所有这三个类别,都定义了Distance

But only for the Line a Distance can be Set. 但仅对于“ Line可以设置Distance

Is there a possibility to build a common abstract (MustInherit) class Segment , having a Distance as (abstract +? ReadOnly ) member? 是否有可能建立一个通用的抽象 (MustInherit)类Segment ,将Distance作为(抽象+? ReadOnly )成员?

Question for VB.NET , but C# answers welcomed too. 对于VB.NET的问题,但C#也欢迎您回答。


Business Background 商业背景

Imagine a Bus. 想象一辆公共汽车。 It has a lot of Station s, MainStation s, and 2 TerminalStation s. 它有很多StationMainStation和2 TerminalStation So Line is between 2 Stations, PoliLine is between 2 MainStation s, and SuperPoliLine is between 2 TerminalStations. 因此, Line在2个工作站之间, PoliLine在2个MainStation之间, SuperPoliLine在2个TerminalStation之间。 All "lines" are "Segments", but only the distance A->B between 2 stations - Line can be defined. 所有“线”均为“段”,但只能定义两个站之间的距离A-> B- 线

You can't override and re-declare (to add the set) at the same time - but you can do: 您不能同时覆盖并重新声明(添加集合),但是您可以执行以下操作:

Base class: 基类:

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

Derived class: 派生类:

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

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

Now you can also override FooImpl as needed. 现在,您还可以根据需要覆盖FooImpl。

Since you want it settable in one class but unsettable in the others, I would customarily not use a property for the one that is “special” (the setter in this case). 由于您希望它在一个类中可设置但在其他类中不可设置,因此我通常不对“特殊”类(在此情况下为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
        }
    }
}

EDITED VERSION: 编辑版本:

    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