Protected readonly field vs protected property
I have an abstract class and I'd like to initialize a readonly field in its protected constructor. I'd like this readonly field to be available in derived classes.
Following my habit of making all fields private and exposing properties, I implemented this as follows:
abstract class Foo
{
private readonly int _field;
protected Foo(int field)
{
_field = field;
}
protected int Field
{
get { return _field; }
}
}
But then I wondered if there is really much advantage of keeping the field private here. I'm aware of the advantages of properties and there are several SO questions on this issue in general, but they focus on public fields as opposed to protected ones.
So should I switch to the below implementation or not? What are the considerations and advantages/disadvantages to be aware of in either case?
abstract class Foo
{
protected readonly int _field;
protected Foo(int field)
{
_field = field;
}
}
Derived classes are still 'users' of the original code; fields should be encapsulated from them too.
You should think of base classes as safe and extendable APIs, rather than just classes which expose their internals. Keep the fields private - apart from anything, it allows the base class to change how that property's value is generated :)
I'd leave the implementation or go with:
protected Field {get; private set;}
(not exactly the same as Field is not readonly for the parent class)
The advantage of properties over fields is they are more future proof. You can change the implementation on the parent class without affecting the children. Without the property you're committed to the field always being readonly. Using fields is frowned upon for another reason, they hurt opacity: the class describes the exact implementation of the field.
So yes, leave the encapsulation.
The only place where I would consider using fields directly for readability is in highly coupled classes such as the states in a state pattern, but in this case the classes themselves would be private.
Readonly properties were implemented in C# 6.0. This is as simple as:
protected Foo(int field)
{
Field = field;
}
protected int Field { get; }
链接地址: http://www.djcxy.com/p/21080.html
上一篇: 如何定义由子类使用的常量?
下一篇: 受保护的只读字段与受保护的属性