属性可以
对内:防止“非常规”的数据污染数据;
对外:向外提供数据,可以是“被加工”以后的数据。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Property
{
class Program
{
static void Main(string[] args)
{
try
{
Person p = new Person();
p.SetAge(200);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.Read();
}
}
}
class Person
{
private int age;
public int GetAge()
{
return this.age;
}
public void SetAge(int value)
{
if (value >= 0 && value <= 130)
{
this.age = value;
}
else
{
throw new Exception("Wrong Age Setting");
}
}
}
}
当识别到人的年龄设置错误时会抛出异常。
微软用Set、Get访问器代替了以上函数,value是一个上下文关键字,仅在Set访问器中作为关键字。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PRoperty
{
class Program
{
static void Main(string[] args)
{
try
{
Person p = new Person();
p.Age = 200;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.Read();
}
}
}
class Person
{
private int age;
public int Age
{
get
{
return this.age;
}
set
{
if (value >= 0 && value <= 130)
{
this.age = value;
}
else
{
throw new Exception("Wrong Age Setting");
}
}
}
}
}
属性是一种语法糖,比如set是SetAge的简写版本。
propfull+两下 Tab键是属性的完整声明;属性的简略声明prop+两下 Tab键;
通过按Tab修改可供修改的地方。
静态属性:
private static int count;
public static int Count
{
get { return count; }
set
{
if (value >= 0)
count = value;
else
{
throw new Exception("Wrong Count Setting");
}
}
}
Ctrl+r+e可以快速封装字段,将光标放在age上,再快速封装即可。
只读属性:
private bool isAdult;
public bool IsAdult
{
get
{
if (age >= 18)
{
return true;
}
else
{
return false;
}
}
}
可以看出是否成年是不可以被外界所修改的值,同时也体现了通过“加工”年龄,可以实时看出一个人是否成年。
同时,当是否成年经常的被访问的时候,就需要在set年龄的时候就去计算是否成年,如果访问频次低,就可以向上面一样写在get访问器里面:
private int age;
public int Age
{
get
{
return this.age;
}
set
{
if (value >= 0 && value <= 130)
{
this.age = value;
}
else
{
throw new Exception("Wrong Age Setting");
}
this.CalIsAdult();
}
}
private bool isAdult;
public bool IsAdult
{
get
{
return isAdult;
}
}
public void CalIsAdult()
{
if (age >= 18)
isAdult = true;
else
isAdult = false;
}