继承,对象 [英] Inheritance, objects

查看:54
本文介绍了继承,对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我在单击命令框时出现错误?我想获取该特定员工的薪水

Why I am getting an error when i click on the command box?, i want to get the salary of that particular employee

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private System.Windows.Forms.ListBox lstCustomers;
        public Form1()
        {
            InitializeComponent();
            lstCustomers.Items.Add(new Customer("A", "B", DateTime.Now.AddDays(-10)));
            lstCustomers.Items.Add(new Customer("C", "D", DateTime.Now.AddDays(-100)));
            lstCustomers.Items.Add(new Customer("F", "G", DateTime.Now.AddDays(-500)));
            lstCustomers.Items.Add(new Employee("Z", "Y", DateTime.Now.AddDays(-700), 100.00));


        }
        private void lstCustomers_SelectedIndexChanged(object sender, EventArgs e)
        {
            Customer cust = (Customer)lstCustomers.SelectedItem;
            MessageBox.Show("Birth Date: " + cust.BirthDate.ToShortDateString());
        }

        private void InitializeComponent()
        {
            this.lstCustomers = new System.Windows.Forms.ListBox();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // lstCustomers
            // 
            this.lstCustomers.FormattingEnabled = true;
            this.lstCustomers.Location = new System.Drawing.Point(12, 12);
            this.lstCustomers.Name = "lstCustomers";
            this.lstCustomers.Size = new System.Drawing.Size(120, 95);
            this.lstCustomers.TabIndex = 0;
            this.lstCustomers.SelectedIndexChanged += new System.EventHandler(this.lstCustomers_SelectedIndexChanged);
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(170, 31);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(308, 230);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.lstCustomers);
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }


        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (Employee emp in lstCustomers.Items)
            {
                //Employee emp = (Customer)lstCustomers.Items;
                MessageBox.Show(Convert.ToString(emp.Salary),"Salary");

            }

        }

    }
    public class Customer
    {
        public string FirstName;
        public string LastName;
        public DateTime BirthDate;

        public Customer() { }

        public Customer(string firstName, string lastName, DateTime birthDate)
        {
            FirstName = firstName;
            LastName = lastName;
            BirthDate = birthDate;
        }

        public override string ToString()
        {
            return FirstName + " " + LastName;
        }
    }

    public class Employee : Customer
    {
        //public string FirstName;
        //public string LastName;
        //public DateTime BirthDate;
        public double Salary;

        public Employee() { }



        public Employee(string firstName, string lastName, DateTime birthDate, double salary)
            :base(firstName,lastName,birthDate)

        {
            Salary = salary;
            //FirstName = firstName;
            //LastName = lastName;
            //BirthDate = birthDate;
        }

        public override string ToString()
        {
            return base.ToString() + " " + Salary ;
        }
    }



}

推荐答案

lstCustomers.Items.Add(new Customer("A", "B", DateTime.Now.AddDays(-10)));
lstCustomers.Items.Add(new Customer("C", "D", DateTime.Now.AddDays(-100)));
lstCustomers.Items.Add(new Customer("F", "G", DateTime.Now.AddDays(-500)));
lstCustomers.Items.Add(new Employee("Z", "Y", DateTime.Now.AddDays(-700), 100.00));


private void button1_Click(object sender, EventArgs e)
{
    foreach (Employee emp in lstCustomers.Items)
    {
        //Employee emp = (Customer)lstCustomers.Items;
        MessageBox.Show(Convert.ToString(emp.Salary),"Salary");
    }
}


因此:您将Customer和Employee项目都添加到ListBox中.很好.
问题是,当您尝试访问它们时,您会得到一个异常:


So: You add both Customer and Employee items to your ListBox. That''s fine.
The problem is when you try to access them, you get an exception:

System.InvalidCastException occurred
  Message="Unable to cast object of type ''Customer'' to type ''Employee''."

仅仅是因为您可以编写代码,并不意味着编译器就能做到!

当您执行foreach时,代码将遍历列表,然后依次将每个变量分配给变量.如果它们的类型不同(并且Employee和Customer不同),则尝试进行强制转换.而且它做不到.您不能从基类转换为派生类.所以,它抱怨.

相反,请遍历基类,并检查您拥有的类型:

Just because you can write code, doesn''t mean the compiler will be able to do it!

When you do a foreach the code iterates through the list and assigns each one to the variable in turn. If they are not the same type (and Employee and Customer are not the same) tthen it attempts to cast. And it can''t do it. You can''t cast from a base class to a derived class. So, it complains.

Instead, iterate through the base class, and check what type you have:

foreach (Customer cust in list.Items)
    {
    Employee emp = cust as Employee;
    if (emp != null)
        {
        Console.WriteLine(emp.name);
        }
    }


这篇关于继承,对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆