从表单更新字段

时间:2013-07-17 03:31:24

标签: c#

我对这个程序有一个小问题。该程序旨在使用多态。我写了一个基类和两个派生类。

我们应该创建一个基类(银行帐户)数组,并用三个银行帐户对象填充它。然后,我们使用它的重载构造函数为每个银行帐户对象分配一个新对象。

 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编号和引脚编号时,问题出现了,这些编号是进入我的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?
     }

当单击按钮时,确保将传递的值更新为表单中的当前值的更好方法是什么?

1 个答案:

答案 0 :(得分:1)

你可以这样写:

private void assignPinNumber(BankAcct account, int newPinNumber)
{
   SilverBankAcct silver = account as SilverBankAcct;
   if(silver != null)
      silver.pinNumber = newPinNumber;
}