1

我在 C# 中编程时遇到此错误:“BankSystem.Account”不包含采用 0 个参数的构造函数

我的课程是:

首先,Account 类:

 public abstract class Account : IAccount
{

    private static decimal minIncome = 0;
    private static int minAge = 18;

    private string name;
    private string address;
    private decimal age;
    private decimal balance;

    public Account(string inName, decimal inAge, decimal inBalance, string inAddress)
    {
        if (AccountAllowed(inBalance, inAge))
        {
            name = inName;
            address = inAddress;
            balance = inBalance;
            age = inAge;

            Console.WriteLine("We created the account. \nName is " + name + " \nThe address is: "
            + address + "\nThe balance is " + balance);

        }
        else
        {
            Console.WriteLine("We cann't create the account. Please check the balance and age!");
        }
    }

    //public CustomerAccount(string newName, decimal initialBalance)

    public Account(string inName, decimal initialBalance)
    {
    }

其次,CustomerAccount 类:

 public class CustomerAccount : Account
{
    private decimal balance = 0;
    private string name;

    public CustomerAccount(string newName, decimal initialBalance)
    {
        name = newName;
        balance = initialBalance;
    }

    public CustomerAccount(string inName, decimal inAge, decimal inBalance, string inAddress)
        : base(inName, inAge)
    {

        // name = inName;
        //age = inAge;
    }

    public CustomerAccount(string inName, decimal inAge)
        : base(inName, inAge)
    {

        // name = inName;
        //age = inAge;
    } ......
4

4 回答 4

7

因为你在你的类中定义了带参数的构造函数,所以默认不会得到默认的构造函数。

您的帐户类已定义构造函数:

public Account(string inName, decimal inAge, decimal inBalance, string inAddress)
public Account(string inName, decimal initialBalance)

您可以定义一个默认构造函数,例如。

public Account() 
{
}

您得到的错误是因为,您的以下构造函数CustomerAccount隐式调用 Account 基类的默认构造函数,因为您没有指定任何其他基构造函数,例如:base(arg1,arg2);

 public CustomerAccount(string newName, decimal initialBalance)
    {
        name = newName;
        balance = initialBalance;
    }

以上与以下相同:

 public CustomerAccount(string newName, decimal initialBalance) : base()
于 2012-06-25T09:46:12.937 回答
7

您也需要在此处“链接”到基本构造函数:

public CustomerAccount(string newName, decimal initialBalance)
    : base(newName, 0)    // something like this
{
    name = newName;
    balance = initialBalance;
}
于 2012-06-25T09:48:04.193 回答
4

简单的。您的Account课程不包含零参数的构造函数,例如

public Account()
{

}

答案在错误消息中。

当您创建Account类的新实例时,请传入正确的参数,例如

Account account = new Account("John Smith", 20.00);

或者创建一个接受零参数的构造函数。

于 2012-06-25T09:52:03.960 回答
1

您正在Account像这样初始化您的课程

new Account();

但应该做

new Account("name", ...);

根据您的构造函数定义。

于 2012-06-25T09:46:40.607 回答