Nel*_*mel 6 c# overriding properties access-modifiers
我正在覆盖我的派生类中的一个属性,我想让它只读.C#编译器不允许我更改访问修饰符,因此它必须保持公开.
最好的方法是什么?我应该扔进InvalidOperationException去set { }吗?
让setter InvalidOperationException在派生类中抛出一个违反了Liskov Subsitution Principle.本质上是将setter contextual用于基类的类型,这基本上消除了多态的价值.
派生类必须尊重它的基类合同.如果setter在所有情况下都不合适,那么它不属于基类.
解决这个问题的一种方法是稍微破坏层次结构.
class C1 {
public virtual int ReadOnlyProperty { get; }
}
class C2 {
public sealed override int ReadOnlyProperty {
get { return Property; }
}
public int Property {
get { ... }
set { ... }
}
}
Run Code Online (Sandbox Code Playgroud)
您遇到问题的类型可以C1在此方案中继承,其余类型可以转换为派生自C2
您可以隐藏原始实现并返回基本实现:
class Foo
{
private string _someString;
public virtual string SomeString
{
get { return _someString; }
set { _someString = value; }
}
}
class Bar : Foo
{
public new string SomeString
{
get { return base.SomeString; }
private set { base.SomeString = value; }
}
}
namespace ConsoleApplication3
{
class Program
{
static void Main( string[] args )
{
Foo f = new Foo();
f.SomeString = "whatever"; // works
Bar b = new Bar();
b.SomeString = "Whatever"; // error
}
}
}
Run Code Online (Sandbox Code Playgroud)
然而,。正如贾里德所暗示的,这是一种奇怪的情况。为什么不首先在基类中将 setter 设置为私有或受保护呢?