c#对象生命周期

d1135130491 2017-11-24 10:08:57
在方法内实例对象,当方法调用结束后,gc就把对象的引用回收了,我输入的数据也找不到了,请问怎么才能让对象不被回收,在原有的代码基础上

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 实验4
{
class Student//学生类
{
string name;
string id;
string english;
string chinese;
string math;

public string Name
{
set { name = value; }
get { return name; }
}
public string Id
{
set { id = value; }
get { return id; }
}
public string English
{
set { english = value; }
get { return english; }
}
public string Chinese
{
set { chinese = value; }
get { return chinese; }
}
public string Math
{
set { math = value; }
get { return math; }
}

}

public class manager//管理类
{
static int num = 0;
Student[] student = new Student[10];
public void addStudent()//添加学生信息
{
student[num] = new Student();
Console.Write("\t\t\t\t请输入姓名:");
student[num].Name = Console.ReadLine();
Console.Write("\t\t\t\t请输入学号:");
student[num].Id = Console.ReadLine();
Console.Write("\t\t\t\t请输入英语成绩:");
student[num].English = Console.ReadLine();
Console.Write("\t\t\t\t请输入语文成绩:");
student[num].Chinese = Console.ReadLine();
Console.Write("\t\t\t\t请输入数学成绩:");
student[num].Math = Console.ReadLine();
Console.WriteLine("\t\t\t\t**添加成功!**");
}

public void alterStudent()
{
string xh;
string item;
Console.WriteLine("修改成绩,需要输入学号:");
xh = Console.ReadLine();
for (int i = 0; i <= num; i++)
{
if (student[num].Id == xh)
{
Console.WriteLine("请输入要修改的项目:");
item = Console.ReadLine();
if (item == "英语")
{
Console.WriteLine("请输入新成绩:");
student[num].English = Console.ReadLine();
}
else if (item == "语文")
{
Console.WriteLine("请输入新成绩:");
student[num].Chinese = Console.ReadLine();
}
else if (item == "数学")
{
Console.WriteLine("请输入新成绩:");
student[num].Math = Console.ReadLine();
}
}
}
}
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 实验4
{
class Program
{
static void Main(string[] args)
{
int functionSelect;
while (true)
{
Console.WriteLine("\t\t\t*********************************");
Console.WriteLine("\t\t\t*\t学生信息管理系统\t*");
Console.WriteLine("\t\t\t*\t\t\t\t*"); ;
Console.WriteLine("\t\t\t*\t\t\t\t*");
Console.WriteLine("\t\t\t* 1.添加 2.修改 3.删除 4.查询 *");
Console.WriteLine("\t\t\t*********************************");
functionSelect = Convert.ToInt32(Console.ReadLine());
manager m = new manager();
switch (functionSelect)
{
case 1:
m.addStudent();
break;
case 2:
m.alterStudent();
break;
case 3:
break;
case 4:
break;
}
}
}
}
}



...全文
189 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
d1135130491 2017-11-25
  • 打赏
  • 举报
回复
跪了,我一个星期没解决的问题,你一句话就解决了。
threenewbee 2017-11-24
  • 打赏
  • 举报
回复
manager m = new manager(); 没有必要每次初始化一次 放在 Main函数的开头

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧