字段:也叫成员变量,必须是名词 field:地域 -空间–计算机程序的本源 最好都是private 或者 protected
实例字段 表示的是实例对象的状态
静态字段 static 表示的是类型当前的状态
以下是程序演示
class Program
{
static void Main(string[] args)
{
List<Student> stuList = new List<Student>();
for (int i = 0; i < 100; i++)
{
Student stu = new Student();
stu.Age = 15 + i;
stu.Score = 60 + i;
stuList.Add(stu);
}
int totalAge = 0;
int totalScore = 0;
foreach (var stu in stuList)
{
totalAge += stu.Age;
totalScore += stu.Score;
}
Student.AverageAge = totalAge / Student.Amount;
Student.AverageScore = totalScore / Student.Amount;
Student.AmoutReport();
Student.AverageAgeReport();
Student.AverageScoreReport();
Student.AmoutReport();
}
}
class Student
{
public int ID;
public string Name;
public int Score;
public int Age;
public static int AverageAge;
public static int AverageScore;
public static int Amount;
//构造函数
public Student()
{
Student.Amount++;
}
public static void AmoutReport()
{
Console.WriteLine(Student.Amount);
}
public static void AverageAgeReport()
{
Console.WriteLine(Student.AverageAge);
}
public static void AverageScoreReport()
{
Console.WriteLine(Student.AverageScore);
}
}
索引器:有人建议在网上再找找
主要用在集合类型上
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> scoreDictionary = new Dictionary<string, int>();
//int? 是可空类型
public int? this[string subject]
{
get {
/* return the specified index here */
if (this.scoreDictionary.ContainsKey(subject))
{
return this.scoreDictionary[subject];
}
else
{
return null;
}
}
set {
/* set the specified index to value here */
if (value.HasValue == false)
{
throw new Exception("kongzhi ");
}
if (this.scoreDictionary.ContainsKey(subject))
{
this.scoreDictionary[subject] = value.Value;
}
else
{
this.scoreDictionary.Add(subject, value.Value);
}
}
}
}