如何在 C# 中初始化 child class 而无需初始化基 class

How to initialize a child class without initializing base class in C#

所以,我有以下 parent class;

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

和下面的child class;

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

我知道 Child class 的构造函数会自动调用 : base()(或者你从 [=25= 内部调用 parent 的构造函数] class)。有没有办法在不初始化的情况下获取 parent 的所有静态函数? (也许使用接口?)从 child class 内部调用 parents 构造函数的方法是什么(可能使用某些参数)?

谢谢。

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

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

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

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

你应该能写出我认为更简洁明了的方式:

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)