C#基础问题希望得到您的帮助谢谢
class Student
{
#region 姓名
private string name;
/// <summary>
/// 姓名
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
#endregion
#region 学号
private string xuehao;
/// <summary>
/// 学号
/// </summary>
public string Xuehao
{
get { return xuehao; }
set { xuehao = value; }
}
#endregion
#region 年龄
private int age;
/// <summary>
/// 年龄
/// </summary>
public int Age
{
get { return age; }
set { age = value; }
}
#endregion
#region 性别
private string sex;
/// <summary>
/// 性别
/// </summary>
public string Sex
{
get { return sex; }
set
{
if(value=="男"||value=="女")
{
sex = value;
}
}
}
#endregion
public Student(string name, string xuehao, int age)
{
this.name = name;
this.xuehao = xuehao;
this.age = age;
}
public void SayHi()
{
Console.WriteLine("我叫" + this.name + "我的学号" + this.xuehao + "我的年龄" + this.age);
}
public void SayHi1()
{
Console.WriteLine("我叫" + this.name + "我的学号" + this.xuehao + "我的年龄" + this.age+"我是"+this.sex);
}
public Student(string name, string xuehao, int age, string sex)
: this(name, xuehao, age)
{
this.sex = sex;
}
}
这里是Main函数
Student s1 = new Student("张三", "110", 20);
Student s2 = new Student("李四", "111", 21,"男");
s2.SayHi1();
s1.SayHi();
Console.Read();
问题:通过构造函数,对私有字段赋值,在属性里设置了条件,只有男或女才允许被赋值,这样这个限制条件是不是不起作用了,必须通过在主函数里this.Sex="男"; 希望大手解决一下,谢谢
------解决方案--------------------属性就是用来做这个的
在属性里可以做判断
给属性赋值
Sex = sex;
------解决方案--------------------构造函数:
public Student(string name, string xuehao, int age, string sex)
: this(name, xuehao, age)
{
this.sex = sex;改为:this.Sex = sex;
}