一道C#难题

来源:百度知道 编辑:UC知道 时间:2024/07/02 04:30:34
using System;
namespace __2
{
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;
public string name;
public Student(string n)
{
name = n;
Console.WriteLine("创建对象个数:{0}",++objects);
}
}
改写函数 计算内存中学生对象的个数;

Student s1 = new Student("王小红");->1
Student s2 = new Student("周军");->2
s1 = new Student("Jerry");->3
s1 = new Student("Jerry");->4
s1 = new Student("王小红");->5
如果改成上面的代码,你需要的结果应该是3吧
============================================================
如果用一个static数组保存人名字,不重复才++objects是否能达到你的要求

objects不就是个数吗?

源代码如下。使用析构函数就可以调查内存中的学生个数了

using System;
namespace __2
{
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;
public string name;
public Student(string n)
{
name = n;