我遇到了一個小程序問題。該程序旨在使用多態。我寫了一個基類和兩個派生類。正在更新字段
我們應該創建一個基類(銀行帳戶)數組,並用三個銀行帳戶對象填充該數組。然後,我們使用它的重載構造函數爲每個銀行賬戶對象分配一個新對象。
public partial class Form1 : Form
{
//Base class array
BankAcct[] b = new BankAcct[3];
public Form1()
{
InitializeComponent();
//This is not getting current values from form!
int accountNum;
int atmNum;
int pinNum;
an = Convert.ToInt32(accountNumber.Text);
p = Convert.ToInt32(pin.Text);
atm = an - p;
//base class
b[0] = new BankAcct(name.Text, 500.00M, accountNum);
//this derived class inherits from bankAcct name, account number, and
//the decimal which is the balance assigned to the Account
//private variables are atm and pin in this class
b[1]= new SilverBankAcct(name.Text, an, 1500.00M, atmNumber, pinNum);
//this derived class inherits from SilverBankAcct atm, pin,
//has one private variable the decimal at the end which is the interest
b[2] = new GoldBankAcct(name.Text, accountNum, 25000.00M, atm, pinNum, 0.05M);
}
我的問題是,當我實例在Form1構造我的對象的字段不從形式更新和在這些領域的當前值被忽略。我嘗試通過訪問我的基類中的屬性並從表單中分配值來分配信息,但是當我嘗試更新我的atm號碼和pin號碼(這些號碼是進入我的SilverBankAcct類的私有變量)和GoldBankAcct類時。
private void button1_Click(object sender, EventArgs e)
{
b[0].fName = name.Text;
b[1].fName = name.Text;
b[2].fName = name.Text;
//do the same for account number which works, but how am I supposed to update atm and pin from the form when I have no access to these variables I only have access to the base class?
}
什麼會是一個更好的方法,以確保被一起傳遞點擊按鈕時,正在更新,從形式的當前值的值?
調試代碼ANS看看會發生什麼......也請讓您的生活更輕鬆,不縮短代碼中的任何字 - 即'an'不變量的名字非常好,因爲很難猜測它的含義。或者'Acct' - 保存3個字符並生成不可讀的標識符不會讓你的代碼更好。 –
對不起,我剛剛編輯它。 –
看起來你有一個設計問題,你必須讓所有你想從課堂外訪問的成員都可用,只有這樣你才能做到想要達到的目標。如果你不通過公共財產暴露成員,它不可能訪問它們嗎? – seshuk