无法弄清楚为什么值没有改变
Can't figue out why the value didn't change
我是 OOP 和 C# 的新手。
我曾尝试使用继承和封装概念,但卡住了。
无法弄清楚为什么当我通过 Atm_1 class.
调用 Deposit 方法时它不起作用
parent class
class Atm
{
public int TotalBalance { get; private set; } = 1000;
public Atm() { }
public void DepoSit(int deposit) { TotalBalance += deposit; }
}
child class
class Atm_1:Atm
{
}
主要
class Program
{
static void Main()
{
var atm = new Atm();
var atm_1 = new Atm_1();
//Before Deposit
Console.WriteLine("Total Balance is "+atm.TotalBalance); //1000
//Deposit
atm_1.DepoSit(20);
//After Deposit
Console.WriteLine("Total Balance is " + atm.TotalBalance); //Still 1000 ??
atm.DepoSit(500);
Console.WriteLine("Total Balance is " + atm.TotalBalance); //Now 1500
//This Works -why the above didn't work?
}
}
Atm_1
继承了Atm
的属性TotalBalance
、构造函数Atm()
和方法DepoSit(int deposit)
,但没有继承你设置的数据至 new Atm();
。
Atm_1
和 Atm
是同一 class 的两个不同实例。尝试将对象 Amt_1
和 Amt
可视化为变量,设置一个变量数据不会更改其他数据。
From Peter Dunniho Comments, I can figure out what i need to do is to create an array instead. Thanks for all comments and answers :)
class Program
{
static void Main(string[] args)
{
Atm[] atm = new Atm[3];
atm[0] = new Atm(50);
atm[1] = new Atm(100000);
atm[2] = new Atm(25);
int totalBalance=0;
for( int i=0;i<atm.Length;i++)
{
totalBalance += atm[i].Balance;
}
Console.WriteLine("TotalBalance is "+totalBalance.ToString("c"));
Console.ReadKey();
}
}
class Atm
{
public int Balance { get; private set; }
public Atm(int balance)
{
Balance=balance;
}
}
我是 OOP 和 C# 的新手。
我曾尝试使用继承和封装概念,但卡住了。
无法弄清楚为什么当我通过 Atm_1 class.
调用 Deposit 方法时它不起作用parent class
class Atm
{
public int TotalBalance { get; private set; } = 1000;
public Atm() { }
public void DepoSit(int deposit) { TotalBalance += deposit; }
}
child class
class Atm_1:Atm
{
}
主要
class Program
{
static void Main()
{
var atm = new Atm();
var atm_1 = new Atm_1();
//Before Deposit
Console.WriteLine("Total Balance is "+atm.TotalBalance); //1000
//Deposit
atm_1.DepoSit(20);
//After Deposit
Console.WriteLine("Total Balance is " + atm.TotalBalance); //Still 1000 ??
atm.DepoSit(500);
Console.WriteLine("Total Balance is " + atm.TotalBalance); //Now 1500
//This Works -why the above didn't work?
}
}
Atm_1
继承了Atm
的属性TotalBalance
、构造函数Atm()
和方法DepoSit(int deposit)
,但没有继承你设置的数据至 new Atm();
。
Atm_1
和 Atm
是同一 class 的两个不同实例。尝试将对象 Amt_1
和 Amt
可视化为变量,设置一个变量数据不会更改其他数据。
From Peter Dunniho Comments, I can figure out what i need to do is to create an array instead. Thanks for all comments and answers :)
class Program
{
static void Main(string[] args)
{
Atm[] atm = new Atm[3];
atm[0] = new Atm(50);
atm[1] = new Atm(100000);
atm[2] = new Atm(25);
int totalBalance=0;
for( int i=0;i<atm.Length;i++)
{
totalBalance += atm[i].Balance;
}
Console.WriteLine("TotalBalance is "+totalBalance.ToString("c"));
Console.ReadKey();
}
}
class Atm
{
public int Balance { get; private set; }
public Atm(int balance)
{
Balance=balance;
}
}