一个关于静态字段的修改问题?
源程序:using System;
namespace P4_4
{
class Program
{
static void Main()
{
Student s1 = new Student("王小红");
Student s2 = new Student("周军");
s1 = new Student("Jerry");
}
}
public class Student
{
public static int objects = 0, classes = 0;
public static string name;
public Student(string n)
{
name = n;
Console.WriteLine("对象计数:{0}", ++objects);
}
static Student()
{
Console.WriteLine("类计数:{0}", ++classes);
}
}
}
在以上程序中,Student的静态字段object_count将记录被创建的学生对象的总数。试修改该程序,使该字段记录的是当前内存中学生对象的总数。
我修改的程序:
using System;
namespace P4_4
{
class Program
{
static void Main()
{
Student s1 = new Student("王小红");
Student s2 = new Student("周军");
s1 = new Student("Jerry");
}
}
public class Student
{
public static int objects = 0, classes = 0,count = 0;
public static string name;
public Student(string n)
{
name = n;
Console.WriteLine("对象计数:{0}", ++objects);
count++;
}
~Student()
{
Console.WriteLine("对象总数:{0}", count);
}
static Student()
{
Console.WriteLine("类计数:{0}", ++classes);
}
}
}
结果如下:
程序运行后出现了三个对象总数,怎么养才能改成显示一个的???