【问题标题】:How to initialize a child class without initializing base class in C#如何在 C# 中初始化子类而不初始化基类
【发布时间】:2021-03-23 08:06:22
【问题描述】:

所以,我有以下父类;

class Parent {
   public Parent() {
      Console.WriteLine ("Parent class")
   }
}

还有下面的子类;

class Child : Parent {
   public Child() {
      Console.WriteLine("Child class")
   }
}

我知道Child 类的构造函数会自动调用: base()(或者您从子类内部调用父类的构造函数)。有没有办法在不初始化父级的情况下获取所有静态函数? (也许使用接口?)从子类内部调用父构造函数的方法是什么(可能带有某些参数)?

谢谢。

【问题讨论】:

  • 静态函数无需创建实例即可使用
  • 我知道,但我的问题是,如何在不自动初始化的情况下从类派生?
  • 如果你可以在父类的构造函数中编辑代码,你可以添加 it(this is Child) { do nothing } else { initialize } 但是...跨度>
  • Child c = new Child{}; 然后c.ParentMethod();?
  • 派生自一个类需要您处理它的构造。请根据您的情况添加详细信息,以便我们推荐不同的方法

标签: c# inheritance constructor parent-child


【解决方案1】:

静态方法在类范围内(不在实例范围内)。所以他们不能被继承。子中调用父构造函数与调用默认构造函数相同。

class Parent {
  public Parent(string param) {
  }
}

class Child : Parent {
  public Child() : base("parameter") {
  }
}

class Child2 : Parent {
  public Child(string param1, int param2) : base(param1) {
  }
}

【讨论】:

  • OP 希望避免在基类中执行所有初始化。
  • 我明白这一点。这个问题有点误导。
【解决方案2】:

你应该能够写出我认为更简单、更干净的方式:

class Parent
{
  public Parent()
  {
    if ( GetType() != typeof(Parent) ) return;
    Console.WriteLine("Parent class");
  }
}

class Child : Parent
{
  public Child()
  {
    Console.WriteLine("Child class");
  }
}

static private void Test()
{
  var instance1 = new Parent();
  Console.WriteLine("-");
  var instance2 = new Child();
}

输出

Parent class
-
Child class

我不建议做这种反 OOP 模式的事情,而是重新考虑类的设计。

但如果有充分的理由这样做,你就完了。

How can I prevent a base constructor from being called by an inheritor in C#? (SO)

How can I prevent a base constructor from being called by an inheritor in C#? (iditect.com)

Ignoring Base Class Constructor (typemock.com)

【讨论】:

    猜你喜欢
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多