using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace 创建和使用对象1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string strID; //声明一个字符串类型的变量
strID=TextBox1.Text; //将TextBox1中的值赋给变量strID
Person2 num1=new Person2(); //创建对象num1
Person num2=num1.fanghui(strID); //创建对象num2,并执行对象num1的fanghui方法,对象num2存放调用方法后返回的值
if(num2!=null) //判断对象num2是否为空
{
string say=num2.sayhello();
Label1.Text=say;
}
else
{
Label1.Text="没有这个员工";
}
}
}
class Person //声明一个类
{
private string Name; //私有字段,封装
private string Sex;
private int Age;
private string Dept;
public Person(string name, string sex, int age, string dept) //带参数构造函数
{
Name = name; //根据传进的参数给私有字段赋值
Sex = sex;
Age = age;
Dept = dept;
}
public string sayhello() //有返回值方法
{
string p1 = "姓名:" + Name + ",性别;" + Sex + ",年龄:" + Age + ",部门:" + Dept;
return p1;
}
}
class Person2 //声明一个类
{
public Person fanghui(string strID) //带参数有返回值方法,此处的返回值类型是类名,因为类是用户自定义的变量类型
{
Person yuwei; //创建一个对象
switch(strID)
{
case "hope001":
yuwei=new Person("于炜","男",23,"技术部"); //满足case"hope001"的条件,执行类Person的构造函数,对象yuwei中存放着("于炜","男",23,"技术部")这些内容
break;
case "hope002":
yuwei=new Person("李四","女",20,"销售部");
break;
case "hope003":
yuwei=new Person("王五","男",25,"维护部");
break;
default:
yuwei=null;
break;
}
return yuwei;
}
}
}
注意:刚开始没有明白“ yuwei=new Person("于炜","男",23,"技术部"); //满足case"hope001"的条件,执行类Person的构造函数,对象yuwei中存放着("于炜","男",23,"技术部")这些内容”这一段的内容。