using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 练习题
{
class student
{
public 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
{
if (value < 20 )
{
Console.WriteLine("年龄不合法!");
age =0;
}
else
{
age =value;
}
}
}
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 void seyhello()
{
Console.WriteLine("姓名为{0}的年龄为{1}性别为{2}", name, age, sex);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 练习题
{
class Program
{
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();
Console.ReadKey();
}
}
}
为什么带参数的重载的字段不经过属性的判断呢?
b 和张三的年龄应该报“不合法”啊,是构造方法的重载不提供属性字段的调用?
你还是没有理解什么叫做属性,属性说白了就是两个方法,set 和get ,你在构造函数中直接给变量赋值根本就没有调用属性 属性怎么会验证你输入的是否合法呢?
这是你声明的变量
private int age;
这是你声明的属性
public int Age
{
get { return age; }
set
{
if (value < 20 )
{
Console.WriteLine("年龄不合法!");
age =0;
}
else
{
age =value;
}
}
}
你的属性就相当于下面的方法
public int GetAge() //get 访问器
{
return age;
}
public void SetAge(int value) //set 访问器
{
if (value < 20 )
{
Console.WriteLine("年龄不合法!");
age =0;
}
else
{
age =value;
}
}你给属性赋值或者是读取属性的值都相当于调用这两个方法。
你在构造函数里根本就没有对属性进行操作,也就是说根本就没有调用方法。
那么它就不可能执行你方法里面的代码。