class Student
{
public int Age;
public int Score;
public static int AverageAge;
public static int AverageScore;
public static int Amount;
public Student()
{
Student.Amount++;
}
public static void ReportAmount()
{
Console.WriteLine(Student.Amount);
}
}
字段的声明
字段的初始值
只读字段
class Program
{
static void Main(string[] args)
{
Student stu1 = new Student();
stu1.SetAge(20);
Student stu2 = new Student();
stu2.SetAge(20);
Student stu3 = new Student();
stu3.SetAge(20);
int avgAge = (stu1.GetAge() + stu2.GetAge() + stu3.GetAge())/3;
Console.WriteLine(avgAge);
}
}
class Student
{
private int age;
public int GetAge()
{
return int this.age;
}
public void SetAge(int value)
{
if(value>0 && value<=120)
{
this.age = value;
}
else
{
throw new Exception("Age value has error.");
}
}
}
属性↓
class Program
{
static void Main(string[] args)
{
try
{
Student stu1 = new Student();
stu1.Age = 20;
Student stu2 = new Student();
stu2.Age = 20;
Student stu3 = new Student();
stu3.Age = 20;
int avgAge = (stu1.Age + stu2.Age + stu3.Age)/3;
Console.WriteLine(avgAge);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
class Student
{
private int age;
public int Age
{
get
{
return this.age;
}
set
{
if(value>0 && value<=120)
{
this.age = value;
}
else
{
throw new Exception("Age value has error.");
}
}
}
}
属性的声明
属性与字段的关系
class Student
{
private Dictionary<string, int> scoreDictionary = new Dictionary<string, int>();
public int? this[string subject]
{
get
{
if(this.scoreDictionary.ContainKey(subject))
{
return this.scoreDictionary(subject);
}
else
{
return null;
}
}
set
{
if(value.HasValue == false)
{
throw new Exception("Score cannot be null.");
}
if(this.scoreDictionary.ContainsKey(subject))
{
this.scoreDictionary(subject) = value.Value;
}
else
{
this.scoreDictionary.Add(subject, value.Value);
}
}
}
}
什么是常量
常量的声明
各种“只读”的应用场景
class Program
{
static void Main(string[] args)
{
Console.WriteLine(WASPEC.WebsiteURL);
}
}
class WASPEC
{
public const string WebsiteURL = "http://www.waspec.org";
}