【发布时间】:2016-04-06 05:31:03
【问题描述】:
我是 C# 的新手,想知道如何测试这个示例代码。换句话说,为了测试 Account.cs(基类)和 SavingsAccount.cs(派生类)中的代码,我在我的主 (Program.cs) 文件中放了什么?如果有意义的话,我想传递数字并让程序输出 Account.cs 和 SavingsAccount.cs 文件中的 ToString。
Account.cs 文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestCode
{
public class Account
{
protected double interestRate;
protected string owner;
protected decimal balance;
public Account(string o, decimal b, double ir)
{
this.interestRate = ir;
this.owner = o;
this.balance = b;
}
public Account(string o, double ir) :
this(o, 0.0M, ir)
{
}
public virtual decimal Balance
{
get { return balance; }
}
public virtual void Withdraw(decimal amount)
{
balance -= amount;
}
public virtual void Deposit(decimal amount)
{
balance += amount;
}
public virtual void AddInterests()
{
balance += balance * (Decimal)interestRate;
}
public override string ToString()
{
return owner + "'s account holds " +
+balance + " kroner";
}
}
}
SavingsAccount.cs 文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestCode
{
public class SavingsAccount : Account
{
public SavingsAccount(string o, double ir) :
base(o, 0.0M, ir)
{
}
public SavingsAccount(string o, decimal b, double ir) :
base(o, b, ir)
{
}
public override void Withdraw(decimal amount)
{
if (amount < balance)
balance -= amount;
else
throw new Exception("Cannot withdraw");
}
public override void AddInterests()
{
balance = balance + balance * (decimal)interestRate
- 100.0M;
}
public override string ToString()
{
return owner + "'s savings account holds " +
+balance + " kroner";
}
}
}
Program.cs 文件(我在这里写什么?):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestCode
{
class Program
{
static void Main(string[] args)
{
SavingsAccount savingsaccount = new SavingsAccount("John", 0.0M, 0.70);
savingsaccount.ToString();
}
}
}
感谢您的帮助!
【问题讨论】:
-
我建议您在构造函数中正确命名变量。这是一个很好的做法。如果您打算在一年内查看代码,那么如果项目变得很大,那将没有任何意义。
-
也许你应该在你的 Main 方法中添加一个
Console.WriteLine(savingsaccount.ToString());。您所做的只是创建字符串,但什么也不做。 -
@Booser 谢谢! Console.WriteLine 工作正常。
标签: c# class oop inheritance polymorphism