简体   繁体   中英

How to call a constructor within a method in C#

The scenario is

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.

The code i have used is like

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();
}

But this keeps throwing error . I have no idea how to call a constructor within a method in the same class

For the method to be factory , it should have the return type of BankAccount . Within that method the private constructor is available and you may use it to create a new instance:

    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;
        }
    }

You should actually create a new instance of BankAccount in that method and return it:

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 BankAccount CreateNewAccount()
{
    Console.WriteLine("\nCreating a new bank account..");
    return new BankAccount();
}

使用'new'运算符:

Foo bar = new Foo();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM