首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从表单更新字段

从表单更新字段
EN

Stack Overflow用户
提问于 2013-07-17 11:31:24
回答 1查看 121关注 0票数 1

我在这个程序上有个小问题。这个程序被设计为使用多态性。我已经写了一个基类和两个派生类。

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

代码语言:javascript
运行
复制
 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类的私有变量。

代码语言:javascript
运行
复制
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?
     }

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-17 12:01:50

你可以这样写:

代码语言:javascript
运行
复制
private void assignPinNumber(BankAcct account, int newPinNumber)
{
   SilverBankAcct silver = account as SilverBankAcct;
   if(silver != null)
      silver.pinNumber = newPinNumber;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17690612

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档