C#继承问题

JL.*_*JL. 6 c# inheritance

我有一个有私人领域的班级......(汽车)

然后我继承了这个班......(奥迪)

在(奥迪)课上,当我打字时.在构造函数中......

私人领域不可用......

我是否需要做一些特殊的事情来揭示(汽车)类中的这些私有字段,以便通过它可以访问它们.在(奥迪班)?

Mar*_*ell 20

一个(坏)选项是制作字段protected- 但不要这样做; 它仍然打破了适当的封装.两个不错的选择:

  • 使得二传手受到保护
  • 提供一个接受值的构造函数

例子:

public string Name { get; protected set; }
Run Code Online (Sandbox Code Playgroud)

(C#2.0)

private string name;
public string Name {
    get { return name; }
    protected set { name = value; }
}
Run Code Online (Sandbox Code Playgroud)

要么:

class BaseType {
  private string name;
  public BaseType(string name) {
    this.name = name;
  }
}
class DerivedType : BaseType {
  public DerivedType() : base("Foo") {}
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 17

菲利普的建议是宣布这些领域protected而不是private确实有效 - 但我建议你不要这样做.

为什么派生类需要关心数据存储方式的实现细节?我建议你公开那些(当前)由这些字段支持的受保护属性,而不是暴露字段本身.

我将您公开的API视为与您向其他类型公开的API非常相似 - 它应该是比您稍后可能想要更改的实现细节更高级别的抽象.


Phi*_*ert 11

您应该将它们声明为"受保护"而不是私有

  • IMO,使字段"受保护"是一个不好的想法. (13认同)

Mar*_*tke 5

您可能正在寻找一种称为构造函数继承的概念.您可以将参数转发给基类构造函数 - 请参阅此示例,其中奥迪有一个标志,指示它是否是S-Line版本:

namespace ConstructorInheritance
{
    abstract class Car
    {
        private int horsePower;
        private int maximumSpeed;

        public Car(int horsePower, int maximumSpeed)
        {
            this.horsePower = horsePower;
            this.maximumSpeed = maximumSpeed;
        }
    }

    class Audi : Car
    {
        private bool isSLineEdition = false;

        // note, how the base constructor is called _and_ the S-Line variable is set in Audi's constructor!
        public Audi(bool isSLineEdition, int horsePower, int maximumSpeed)
            : base(horsePower, maximumSpeed)
        {
            this.isSLineEdition = isSLineEdition;
        }
    }

    class Program
{
    static void Main(string[] args)
    {
        Car car = new Audi(true, 210, 255);
        // break here and watch the car instance in the debugger...
    }
}    }
Run Code Online (Sandbox Code Playgroud)