你是我的朋友吧?
还是帮帮你吧,希望对你有帮助。
主窗体:
程序代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
namespace PersonEx
{
public partial class MainForm : Form
{
private MiddleSchoolStudent stu;
private Worker worker;
public MainForm()
{
InitializeComponent();
stu = new MiddleSchoolStudent();
worker = new Worker();
}
private void SetStuAgeButton_Click(object sender, EventArgs e)
{
try
{
int stuAge = int.Parse(this.StudentAgeTextBox.Text);
stu.SetAge(stuAge);
MessageBox.Show("设置成功!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void SetWorkerAgeButton_Click(object sender, EventArgs e)
{
try
{
int workerAge = int.Parse(this.WorkerAgeTextBox.Text);
worker.SetAge(workerAge);
MessageBox.Show("设置成功!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Person超类:
程序代码:
using System;
namespace PersonEx
{
public abstract class Person
{
protected string _name;
protected string _workType;
protected int _age;
public abstract int GetAge();
public abstract void SetAge(int Age);
}
}
MiddleSchoolStudent类:
using System;
namespace PersonEx
{
class MiddleSchoolStudent : Person
{
public override int GetAge()
{
return this._age;
}
public override void SetAge(int Age)
{
if (Age > 30)
{
throw new Exception("The MiddleSchoolStudent's Age can't greater than 30!Setting failure");
}
else
{
this._age = Age;
}
}
}
}
Woker类:
using System;
using System.Collections.Generic;
namespace PersonEx
{
class Worker:Person
{
public override int GetAge()
{
return this._age;
}
public override void SetAge(int Age)
{
if (Age < 18)
{
throw new Exception("Worker's age can't less than 18! Setting failure!");
}
else
{
this._age = Age;
}
}
}
}