gpt4 book ai didi

c# - 如何在 C# 中的方法中调用构造函数

转载 作者:行者123 更新时间:2023-11-30 13:38:53 26 4
gpt4 key购买 nike

场景是

Hide the constructor of BankAccount. And to allow construction of BankAccount, create a public static method called CreateNewAccount responsible of creating and returning new BankAccount object on request. This method will act as a factory of creating new BankAccounts.

我用过的代码是这样的

private BankAccount()
{
///some code here
}

//since the bank acc is protected, this method is used as a factory to create new bank accounts
public static void CreateNewAccount()
{
Console.WriteLine("\nCreating a new bank account..");
BankAccount();
}

但这一直在抛出错误。我不知道如何在同一个类的方法中调用构造函数

最佳答案

要使方法成为工厂,它的返回类型应该是BankAccount。在该方法中,private 构造函数可用,您可以使用它来创建新实例:

    public class BankAccount
{
private BankAccount()
{
///some code here
}

public static BankAccount CreateNewAccount()
{
Console.WriteLine("\nCreating a new bank account..");
BankAccount ba = new BankAccount();
//...
return ba;
}
}

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

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