gpt4 book ai didi

c# - C# 中的构造函数

转载 作者:行者123 更新时间:2023-11-30 13:44:56 24 4
gpt4 key购买 nike

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

public class Parent
{
public Parent()
{
//some stuffs
}
public Parent(string st)
{
//some stuffs
}
}

现在我有一个带有两个方法的派生类。我必须在一种方法中使用 Parent-constructor,在另一种方法中使用 Parent(string st)。但是这里总是在调用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);
}
}

请告诉我如何做到这一点。提前致谢。

最佳答案

只需在派生类中使用两个构造函数,它们使用基类中的适当构造函数即可。

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

public Derived(string s) : base(s)
{
}
}

:base() 命名法将调用父构造函数。

关于c# - C# 中的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33693253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com