What are the advantages and disadvantages of having a readonly field compared to the fact that inheritors implement the abstract getter-only property (using C # as an example here, but in my opinion, it does not really matter).
Here are two ways to do this:
read-only field heirs need to insert a value into the constructor
interface IFace {
public int Field { get; }
}
abstract class Base : IFace {
private readonly int field;
protected Base(int field) {
this.field = field;
}
public int Field { get { return this.field; } }
}
class Impl {
public Impl() : base(1) {
}
}
abstract property getter-only; Inheritors must implement a property
interface IFace {
public int Field { get; }
}
abstract class Base : IFace {
public abstract int Field { get; }
}
class Impl {
public override int Field { get { return 1; } }
}
Both implementations expose the public property int Fieldgetter-only, which does not change.
However, I see the following differences:
The value is fieldattached to each instance and nothing prevents the heirs from allowing the value to be received in the constructors themselves ( public Impl(int field) : base(field)).
, . , .
: ( ).
() field , / , . public overried int Field { get { return DateTime.UtcNow.Second; } }
" IL", () , ( ).
: ( , , ?). , , : , , .
- , ? , ?
, //, readonly (constant) , . , , ( ). , . ? .