【问题标题】:How to force declaration of variables in base class [closed]如何强制在基类中声明变量[关闭]
【发布时间】:2014-07-15 12:57:41
【问题描述】:

我有一个类 Base 和一个继承 Base, A 的类

public class Base
{
   int baseVal;
      public Base()
      {
      }
}

public class A : Base
{
    int aVal;
       public A()
      {
      }
}

当我创建 A 类型的变量时,如何确保 baseVal 也已初始化?

有一种可能性,我让 A 构造函数也执行 Base 构造函数,如下所示:

public A() : base(0)

但我知道执行 A() 构造函数后 baseVal 的值。那么,我最好的选择是什么?

【问题讨论】:

  • “执行 A() 构造函数后我知道 baseVale 的值”是什么意思?你的问题很不清楚。
  • 例如在 C++ 中:如果接口中有虚拟抽象方法,则必须在继承它的类中初始化它。 @JonSkeet
  • 是的,这就是抽象方法在C#中的用途,但是没有抽象字段之类的东西,我不明白您的评论如何回答我关于“我知道 baseVale 的价值”的问题
  • 如果您通过 public A() : base(var) 初始化一个类,这意味着您首先运行 base(var) 构造函数并在 A 构造函数之后运行。如果我在 A 构造函数中计算 var ,这意味着 base(var) 已经执行,我无法确保我以可以确保某些变量在你想要的方式。我知道我不是很清楚@JonSkeet
  • 那么您需要致电base(SomeCalculation())。如果你能给我们一个具体的问题来解决,那真的很有帮助......

标签: c# .net class inheritance


【解决方案1】:

如果“执行 A() 构造函数后我知道 baseVal 的值”是指计算类 A 的构造函数中的值,则可以将 baseVal 可访问性更改为 protected 并在末尾分配值A类中的构造函数:

public class Base
{
    protected int baseVal;
    // code ommitted
}

public class A : Base
{
    int aVal;
    public A()
    {
        // calculate the value that you need
        baseVal = //some value that you calculate
    }
}

【讨论】:

    【解决方案2】:

    没有空的构造函数
    如果它受到保护,则可以通过派生类访问它

    public class Base
    {
          protected int baseVal;
          public Base(int BaseVal)
          {
              baseVal = BaseVal;
          }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      • 2016-07-09
      • 1970-01-01
      • 2016-10-28
      相关资源
      最近更新 更多