c# -不能创建抽象类或接口的实例
本文关键字:接口 实例 抽象类 不能 创建 | 更新日期: 2023-09-27 18:10:22
我在c#教程中得到错误Cannot create an instance of the abstract class or interface
。
这一行失败:result = new Account(nameText, addressText, balance);
这是我的班级:
public abstract class Account : IAccount
{
//---------------------------------------------------------------
// Constructor
//---------------------------------------------------------------
public Account(string inName, string inAddress, decimal inBalance)
{
name = inName;
address = inAddress;
balance = inBalance;
}
public Account(string inName, string inAddress) :
this(inName, inAddress, 0) // 'this ties this alternate constructor back to the original constructor (directly above)
{
}
public Account(string inName) : // 'this ties this alternate constructor back to the original constructor (directly above)
this(inName, "Not Supplied", 0)
{
}
//---------------------------------------------------------------
// Properties
//---------------------------------------------------------------
// * * * * * * * *
//global account constraints
private static decimal minIncome = 10000;
private static int minAge = 18;
// * * * * * * * *
//personal details
private string name;
private string address;
// * * * * * * * *
//account details
public int AccountNumber;
public static decimal InterestRateCharged;
public AccountState State;
private decimal balance = 0;
public int Overdraft;
//---------------------------------------------------------------
// Methods
//---------------------------------------------------------------
// loads the account
public static Account Load(string filename)
{
Account result = null;
System.IO.TextReader textIn = null;
try
{
textIn = new System.IO.StreamReader(filename);
string nameText = textIn.ReadLine();
string addressText = textIn.ReadLine();
string balanceText = textIn.ReadLine();
decimal balance = decimal.Parse(balanceText);
result = new Account(nameText, addressText, balance);
}
catch
{
return null;
}
finally
{
if (textIn != null) textIn.Close();
}
return result;
}
};
下面是我的界面:
public interface IAccount
{
// account info
int GetAccountNumber();
string GetName();
decimal GetBalance();
// account actions
void PayInFunds(decimal amount);
bool WithdrawFunds(decimal amount);
string RudeLetterString();
}
这就是抽象类的定义。不能创建它的实例,只能创建从它派生的类型。
想想水果之类的东西。你不能让水果放在桌上。它必须是某种类型的水果,例如橘子或苹果。在这种情况下,fruit将是一个抽象类,并且可以实现所有水果共同的功能和属性。橙子和苹果将从水果类派生,并实现特定于水果类型的功能和属性。
使用abstract
关键字,当它没有意义创建你的类的实例,但你想实现基功能,可以跨派生类型共享。如果你只是想定义一个没有任何共享代码的契约,你可以使用接口。
public abstract class Account : IAccount
删除abstract
如果你只想从你的静态方法中创建一个Account
实例,让构造函数private
或protected
代替。