//自定义类,设定为public,方便但不安全,被他人引用而造成异常(方法1/3)
class User
{
public string name; //设定为public,方便但不安全,被他人引用而造成异常
public string sex;
public void SetSex(string values)
{
if (values == "男" || values == "女")
sex = values;
else
MessageBox.Show("性别只能为''男''或''女''");
}
}
private void button1_Click(object sender, EventArgs e)
{
User zs = new User();
zs.name = "张三丰";
zs.SetSex("人");
MessageBox.Show("姓名:"+zs.name+"性别:"+zs.sex);
}
//自定义类,使用了private,这样会更安全些(方法2/3)
class User //自定义类
{
private string name; //设定为private,相对安全
private string sex;
public void SetName(string values)
{
name = values;
}
public void SetSex(string values)
{
if (values == "男" || values == "女")
sex = values;
else
MessageBox.Show("性别只能为''男''或''女''");
}
public string GetNmae()
{
return name;
}
public string GetSex()
{
return sex;
}
}
private void button1_Click(object sender, EventArgs e)
{
User zs = new User();
zs.SetName("张三丰");
zs.SetSex("人");
MessageBox.Show("姓名:" + zs.GetNmae() + " 性别:" + zs.GetSex());
}
//自定义类,使用了属性(方法3/3)
class User //自定义类
{
private string name;
private string sex;
public String Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Sex
{
get
{
return sex;
}
set
{
if (value == "男" || value == "女")
sex = value;
else
MessageBox.Show("性别只能为''男''或''女''");
}
}
}
private void button1_Click(object sender, EventArgs e)
{
User zs = new User();
zs.Name = "张三";
zs.Sex = "人";
MessageBox.Show("姓名:" + zs.Name + " 性别:" + zs.Sex);
}