使子类中的成员变为只读 [英] Making members in subclasses readonly

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

问题描述

假设我有一个类int为成员number,它具有一个吸气剂和一个吸气剂.

Let's say I have the class A with member int number which has a getter and a setter.

然后,我创建A的子类,并将其称为B.现在,在类B中,我希望保留成员number,但是在该类中,我想强加number是只读的限制.我该怎么办?

Then I make a subclass of A and call it B. Now in the class B I wish to keep the member number, but in this class I want to impose the restriction that number is read-only. How can I do this?

推荐答案

对此的需求通常暗示您的设计不是最佳的(因为它违反了Liskov替换原理).因此,C#并不真正支持它.但是,以下是两种 实现方式:

The need for that is usually a hint that your design is not optimal (as it violates the Liskov substitution principle). Therefore, C# does not really support it. However, here are two ways to kind of implement it:

(1)在后代中隐藏该属性,并提供一个新属性来代替基类的getter.但这并不能真正保护该属性,因为您可以将其强制转换为基类:

(1) Hide the property in the descendent and provide a new property that replaces the getter of the base class. But this does not really protect the property, since you can just cast to the base class:

class A
{
  public int Number { get; set; }
}

class B : A
{
  public new int Number
  {
    get { return base.Number; }
  }
}

B b = new B();
// b.Number = 42; // This does not work.
A a = b;
a.Number = 42;
Console.WriteLine(b.Number); // == 42. Oops.

(2)使用抛出异常的方法覆盖设置器.但是现在使用错误会导致运行时错误,而不是编译器错误,这不是很好.考虑在基础上添加一个bool CanSetNumber属性(.NET与Stream.CanSeekSeek做类似的事情).

(2) Override the setter with an exception throw. But a wrong usage now causes a runtime error instead of a compiler error which is not nice. Consider adding a bool CanSetNumber property to the base (.NET does something similar with Stream.CanSeek and Seek).

class A
{
  public virtual int Number { get; set; }
}

class B : A
{
  public override int Number
  {
    get { return base.Number; }
    set { throw new InvalidOperationException("B.Number is readonly!"); }
  }
}

B b = new B();
b.Number = 42; // BAM!

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

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