情景是
隐藏BankAccount的构造函数.为了允许构造BankAccount,创建一个名为CreateNewAccount的公共静态方法,负责根据请求创建和返回新的BankAccount对象.此方法将充当创建新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();
}
Run Code Online (Sandbox Code Playgroud)
但这不断抛出错误.我不知道如何在同一个类的方法中调用构造函数
对于要出厂的方法,它应该具有返回类型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;
}
}
Run Code Online (Sandbox Code Playgroud)