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

Gir*_*ram 3 c# constructor

情景是

隐藏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)

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

hor*_*rgh 7

对于要出厂的方法,它应该具有返回类型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)

  • @GireeshSundaram,因为这是你的第一个问题,看起来你得到了你想要的答案,你可能会看到:[如何接受答案?](http://meta.stackexchange.com/questions/5234/how-不接受-的回答工作) (3认同)