C#中的构造函数

Ram*_*Ram 3 c# constructor

我有一个带有2个构造函数的父类,派生类试图用2种不同的方法调用父类的构造函数

public class Parent
{
    public Parent()
    {
        //some stuffs
    }
    public Parent(string st)
    {
        //some stuffs
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个带有两个方法的派生类.我必须Parent在一个方法和Parent(string st)其他方法中使用-constructor .但是这里总是调用Parent-constructor.下面是派生类

public class Derived : Parent
{
    public void GetData()
    {
        //Here I initialize the constructor like this
        Parent p = new Parent();
    }

    public void GetData1()
    {
        string s = "1";
        Parent p = new Parent(s);
    }
}
Run Code Online (Sandbox Code Playgroud)

请让我告诉我如何实现这一目标.提前致谢.

Dar*_*ung 5

只需在Derived类中有两个构造函数,它们在基础中使用适当的构造函数.

public class Derived : Parent
{
   public Derived() : base()
   {
   }

   public Derived(string s) : base(s)
   {
   }
}
Run Code Online (Sandbox Code Playgroud)

:base()术语将调用父类的构造.