在C#语言中,类(或结构体)包含以下成员:
internal class Program
{
static void Main(string[] args)
{
// 实例化一个对象
Student stu1 = new Student();
stu1.Age = 40;
stu1.Score = 90;
Student stu2 = new Student();
stu2.Age = 24;
stu2.Score = 60;
Student.ReportAmount(); // >>>2
}
}
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);
}
}
internal class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>();
for (int i = 0; i < 100; i++)
{
Student student = new Student();
student.Age = 24;
student.Score = i;
students.Add(student);
}
int totalAge = 0;
int totalScore = 0;
foreach (Student student in students)
{
totalAge += student.Age;
totalScore += student.Score;
}
Student.AverageAge = totalAge / Student.Amount;
Student.AverageScore = totalScore / Student.Amount;
Student.ReportAmount(); // >>>100
Student.ReportAverageAge(); // >>>24
Student.