初学C#明白怎样设置和调用属性
using System;using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication8
{
class SavingAccount
{
//用于存储帐号\余额和已获利息的类字段
private int _accountNumber;
private double _balance;
private double _interestEarned;
//利率是静态的,因为所有的帐户都使用相同的利率
private static double _interestRate;
//构造函数初始化类成员
public SavingAccount(int _accountNumber, double _balance)
{
this._accountNumber = _accountNumber;
this._balance = _balance;
}
//AccountNumber只读属性
public int AccountNumber
{
get
{
return _accountNumber;
}
}
//Balance只读属性
public double Balance
{
get
{
if ( _balance < 0)
{
Console.WriteLine("无余额");
}return _balance;
}
}
//InterestEarned 读/写属性
public double InterestEarned
{
get
{
return _interestEarned;
}
set
{
//验证数据
if (value < 0.0)
{
Console.WriteLine("利息不能为负数");
return;
}
_interestEarned = value;
}
}
//InterestRate 读/写属性为静态
//因为所有特定类型的帐户都具有相同的利率
public static double InterestRate
{
get
{
return _interestRate;
}
set
{
//验证数据
if (value < 0.0)
{
Console.WriteLine("利率不能为负数");
return;
}
else
{
_interestRate = value / 100;
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication8
{
class TestSavingAccount
{
[STAThread ]
static void Main(string[] args)
{
//创建 SavingAccount 的对象
SavingAccount objSavingAccount = new SavingAccount(12345,5000);
//用户交互
Console.WriteLine("----------------C#第六章示例1--此程序让我明白怎样设置和调用属性-----------------");
Console.WriteLine("输入到现在为止已经获得的利息和利率");
objSavingAccount.InterestEarned = Int64.Parse(Console .ReadLine ());
SavingAccount.InterestRate = Int64.Parse(Console .ReadLine ());
//使用类名访问静态属性
objSavingAccount.InterestEarned += objSavingAccount.Balance * SavingAccount.InterestRate;
Console.WriteLine("获得的总利息为:{0}", objSavingAccount.InterestEarned);
}
}
}