属性中的代码只有调用属性赋值,获取数据时才运行
在构造函数中初始化会直接赋值给成员变量 属性中的逻辑都不会被运行
属性的作用
1.保护成员变量
2.为成员属性的获取和赋值添加逻辑处理(加密处理 或者 限制变量值的范围)
3.可以给成员变量设置只读或者只修改(一般不会设只修改)
4.get和set前可以加访问修饰符,但是有一定规则
{
默认不加时 会使用属性申明的访问权限
加的访问修饰符要低于属性的访问权限
不能让get和set 的访问权限都低于属性的权限
}
5.get和set 可以只有一个
public int age
{
get {里面写return age-5} 红色的是加密和解密
set {里面写value value就是传值的中间站 age=value+5}
}
6.没什么需要特殊处理的可以直接给他 自动属性 就不用声明成员变量了
public int age
{
get;
set;
}
小练习
using System.Runtime.Serialization;
class Student
{
private string name;
private int age;
private bool sex;
private float cSharpScore;
private float UnityScore;
public Student()
{
}
public Student( string name ,int age ,bool sex ,float cSharpScore,float UnityScore)
{
this.name = name;
this.age = age;
this.sex = sex;
this.cSharpScore = cSharpScore;
this.UnityScore = UnityScore;
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get { return age; }
set
{
if (value < 0)
{
Console.WriteLine("太小了");
age = 0;
}
else if (value > 150)
{
age= 150;
}
}
}
public bool Sex
{
get
{
return sex;
}
set
{
sex = value;
}
}
public float CSharpScore
{
get
{
return cSharpScore;
}
set
{
if (value < 0)
{
cSharpScore = 0;
Console.WriteLine("成绩化为0了");
}
else if (value > 100)
{
cSharpScore = 100;
Console.WriteLine("成绩化为100了");
}
else
{
cSharpScore= value;
}
}
}
public float UNityScore
{
get
{
return UnityScore;
}
set
{
if (value < 0)
{
UnityScore = 0;
Console.WriteLine("成绩化为0了");
}
else if (value > 100)
{
UnityScore = 100;
Console.WriteLine("成绩化为100了");
}
else
{
UnityScore = value;
}
}
}
public void SayHello()
{
Console.WriteLine("我叫{0},今年{1}岁了,是{2}同学",name,age,sex?"男":"女");
}
public void AverageAndSumScore()
{
Console.WriteLine("Average Score {0}", (cSharpScore + UnityScore) / 2);
Console.WriteLine("Sum Score{0}",UnityScore+cSharpScore);
}
}
class Program
{
static void Main()
{
Student student = new Student("C",-5,true,-50,50);
student.SayHello();
student.AverageAndSumScore();
Student student1 = new Student();
student1.Age = -9;
student1.CSharpScore =160;
student1.UNityScore = -1;
student1.SayHello();
student1.AverageAndSumScore();
}
}