C#中的构造方法 [英] Constructor in C#
问题描述
我有一个带有2个构造函数的父类,而派生类则试图用2种不同的方法调用parent的构造函数
I have a parent class with 2 constructor and the derived class trying to call the constructor of parent in 2 different methods
public class Parent
{
public Parent()
{
//some stuffs
}
public Parent(string st)
{
//some stuffs
}
}
现在我有一个派生类有两种方法。
我必须在一种方法中使用 Parent
-constructor,在另一种方法中使用 Parent(string st)
。
但这里总是调用 Parent
构造函数。下面是派生类
Now I have a derived class with two methods.
I Have to use Parent
-constructor in one method and the Parent(string st)
in other method.
But here It is always calling the Parent
-constructor. Below is the derived class
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);
}
}
请让我来实现这一目标。
预先感谢。
Please let me how to make this happen. Thanks in advance.
推荐答案
您的Derived类中只有两个构造函数,它们在基础中使用适当的构造函数。
Just have two constructors in your Derived class that use the appropriate constructor in the base.
public class Derived : Parent
{
public Derived() : base()
{
}
public Derived(string s) : base(s)
{
}
}
:base()
命名法将调用父构造函数。
The :base()
nomenclature will invoke the parent constructor.
这篇关于C#中的构造方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!