field表示的是一段空间,字段表示的是内存中的一段空间
[特性] [修饰符]类型 变量声明器;
public int age = 100;//变量声明器是 age=100,age是变量名,=100是初始化器
class Human
{
public static int Age;
static Human()//静态构造器
{
Human.Age = 0;
}
}
//属性声明的格式是[特性] [修饰符] 类型 成员名称 {访问器}
//完整声明和简略声明的区别就在于如何写{访问器}
propfull+tab+tab
prop+tab+tab
只用于传递数据将stu3的年龄不小心设置为200,但是平均年龄是80,也符合人的年龄,但是已经为程序引入了一个很难发现的bug,为了避免该情况,可以把Age设置为private,通过Get和Set方法来进行处理
class Program
{
static void Main(string[] args)
{
Student stu1 = new Student();
Student stu2 = new Student();
Student stu3 = new Student();
stu1.Age = 20;
stu2.Age = 20;
stu3.Age = 200;
int avgAge = (stu1.Age + stu2.Age + stu3.Age) / 3;
}
}
class Student
{
public int Age;
}
以下是经过处理的程序
class Program
{
static void Main(string[] args)
{
Student stu1 = new Student();
Student stu2 = new Student();
Student stu3 = new Student();
stu1.SetAge(20);
stu1.SetAge(20);
stu1.SetAge(20);
int avgAge = (stu1.GetAge() + stu2.GetAge() + stu3.GetAge());
Console.WriteLine(avgAge);
}
}
class Student
{
private int Age;
public int GetAge()
{
return this.Age;
}
public void SetAge(int value )
{
if(value >=0 && value <= 120)
{
this.Age = value;
}
else
{
throw new Exception("Age value has error!");
}
}
}
C#经过改进的写法(添加了value上下文关键字
和set/get访问器
)
class Program
{
static void Main(string[] args)
{
Student stu1 = new Student();
Student stu2 = new Student();
Student stu3 = new Student();
stu1.Age = 20;
stu2.Age = 20;
stu3.Age = 20;
int avgAge = (stu1.Age+stu2.Age+stu3.Age)/3;
Console.WriteLine(avgAge);
}
}
class Student
{
private int age;
public int Age
{
get//get 访问器
{
return this.age;
}
set//set访问器
{
if (value >= 0 && value <= 120)
{
age = value;
}
else
{
throw new Exception("wrong value");
}
}
}
}
使用ildasm(可以去C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\
下找)打开解决方案bin文件夹下的应用程序,展开可以查看最终get和set都是调用了getAge方法
CanWork
的值会根据不同的Age
进行不同的更新
class Student
{
private int age;
public int Age
{
get//get 访问器
{
return this.age;
}
set//set访问器
{
if (value >= 0 && value <= 120)
{
age = value;
}
else
{
throw new Exception("wrong value");
}
}
}
public bool CanWork
{
get {
if (this.age >= 16)
{
return true;
}
else
{
return false;
}
}
}
}
indexer + tab + tab
class Program
{
static void Main(string[] args)
{
Student stu = new Student();
stu["Math"] = 90;
var mathScore = stu["Math"];
Console.WriteLine(mathScore);
}
}
class Student
{
private Dictionary<string, int> scoreDict = new Dictionary<string, int> { };
public int? this[string subject]
{
get {
if (this.scoreDict.ContainsKey(subject))
{
return this.scoreDict[subject];
}
else
{
return null;
}
}
set {
if (value.HasValue == false)
{
throw new Exception("Score can not be null");
}
if (this.scoreDict.ContainsKey(subject))
{
this.scoreDict[subject] = value.Value;
}
else
{
this.scoreDict.Add(subject, value.Value);
}
}
}
}