本帖最后由 Darkhorse′Xa 于 2014-5-15 10:37 编辑
你构造函数里头都是对字段的赋值,所以的话没有进行数据的非法判断
应该把赋值给字段改成赋值属性,这样才会用到setget访问器.
在你代码上修改了一下,可以看一下
- <p>
- static void Main(string[] args)
- {
- Student a = new Student();
- a.Name = "A";
- a.Sex = '男';
- a.Age = 2;
- a.seyhello();
- Student b = new Student("b");
- b.seyhello();
- Student c = new Student("张三", 9, '男');
- c.seyhello();</p><p> Student stu = new Student("李四", 25, '男');//合法数据
- stu.seyhello();
- Console.ReadKey();</p><p>}</p><p> class Student
- {
-
- private int age;
- private string name;
- private char sex;
- public string Name
- {
- get { return name; }
- set { name = value; }
- }
- public int Age
- {
- get { return age; }
- set
- {</p><p> if (value < 20)
- {
- Console.WriteLine("年龄不合法!");
- age = 0;
- }
- else
- {
- age = value;
- }
- }
- }</p><p> public char Sex
- {
- get { return sex; }
- set { sex = value; }
- }
- public Student(string name, int age, char sex)
- {
- this.Name = name;//对属性的赋值,而不是字段,否则你没法进行数据非法判断
- this.Age = age;
- this.Sex = sex;
- }
- public Student(string name)
- {
- this.Name = name;
- this.Age = 2;
- this.Sex = '女';
- }
- public Student()
- {
- }
- public void seyhello()
- {
- Console.WriteLine("姓名为{0}的年龄为{1}性别为{2}", name, age, sex);
- }
- }</p>
复制代码
|