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

标签 c# constructor

场景是

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/

相关文章:

c# - Kendo Mvc DropdownList,如何设置初始值

c# - 使用 Naudio 复制 Wave 文件 - 复制/附加最新的可用字节

c++ - 如何在main()中调用构造函数?

c++ - 将 make_shared 与 protected 构造函数 + 抽象接口(interface)一起使用

templates - 模板化类中的构造函数继承 (C++11)

c# - 在 Html.BeginForm MVC4 Controller 操作中传递多个参数

c# - 从 onchange 触发 .click() 时 IE9 出现 "SCRIPT5 Access is denied"错误

c# - 在 DataTrigger WPF 上开始 Storybard

android - 为什么 View 构造函数需要 Context 对象

java - 通过 Get & Set 与构造函数初始化实例变量