在派生类中使属性只读 [英] Make property readonly in derived class

查看:56
本文介绍了在派生类中使属性只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的派生类中覆盖了一个属性,我想让它成为只读的.C# 编译器不允许我更改访问修饰符,因此它必须保持公开状态.

I'm overriding a property in my derived class that I would like to make it readonly. The C# compiler won't let me change the access modifiers, so it must stay public.

这样做的最佳方法是什么?我应该在 set { } 中抛出一个 InvalidOperationException 吗?

What's the best way to do this? Should I just throw an InvalidOperationException in set { }?

推荐答案

让 setter 在派生类中抛出 InvalidOperationException 违反了 Liskov 替换原则.本质上使 setter 的使用与基类的类型相关,这从根本上消除了多态性的价值.

Having the setter throw an InvalidOperationException in a derived class violates the Liskov Subsitution Principle. Essentially makes the usage of the setter contextual to the type of the base class which essentially eliminates the value of polymorphism.

您的派生类必须遵守其基类的约定.如果 setter 不适用于所有情况,则它不属于基类.

Your derived class must respect the contract of it's base class. If the setter is not appropriate in all circumstances then it doesn't belong on the base class.

解决此问题的一种方法是稍微打破层次结构.

One way to work around this is to break the hierarchy up a little bit.

class C1 { 
  public virtual int ReadOnlyProperty { get; } 
}
class C2 { 
  public sealed override int ReadOnlyProperty { 
    get { return Property; }
  }
  public int Property {
    get { ... }
    set { ... }
  }
}

在这种情况下,您遇到问题的类型可以继承 C1,其余类型可以切换为派生自 C2

Your type you're having problems with could inherit C1 in this scenario and the rest could switch to derive from C2

这篇关于在派生类中使属性只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆