场景是
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/