我在C#中编程时遇到此错误: 'BankSystem.Account'不包含带0参数的构造函数
我的课程是:
首先,帐户类:
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;
} ......
答案 0 :(得分: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()
答案 1 :(得分:7)
你也需要在这里“链接”到基础构造函数:
public CustomerAccount(string newName, decimal initialBalance)
: base(newName, 0) // something like this
{
name = newName;
balance = initialBalance;
}
答案 2 :(得分:4)
简单。您的Account
类不包含具有零参数的构造函数,例如
public Account()
{
}
答案在错误消息中。
在正确的参数中创建Account
类传递的新实例时,例如
Account account = new Account("John Smith", 20.00);
或者创建一个零参数的构造函数。
答案 3 :(得分:1)
您正在初始化Account
这样的课程
new Account();
但应该
new Account("name", ...);
根据你的构造函数定义。