简体   繁体   English

关于C#中“静态”字段的清除

[英]clearance about “static” field in c#

I have commonFields class in my application. 我的应用程序中有commonFields类。 this is online asp.net mvc application of simple test/exam. 这是简单测试/考试的在线asp.net mvc应用程序。 suppose student have logged in with his credentials. 假设学生已使用其凭据登录。 he got select test, and said load it.it will load test in some controller, each test have set of questions. 他得到了选择测试,并说要加载它。它将在某个控制器中加载测试,每个测试都有一系列问题。 now with this test id i get the list of questions of that particular test. 现在有了这个测试ID,我得到了该特定测试的问题列表。 and stored in commonfield class's 并存储在commonfield类的

 public static List<Question> questionList; 

object. 宾语。 due to static it will as it is for application. 由于是静态的,因此将直接用于应用程序。 but if same time another student get logged in and performing the same or different test. 但是如果同一时间另一个学生登录并执行相同或不同的测试。 then his selected test's question will stored into again in the questionList object (same as above). 然后他选择的测试的问题将再次存储在questionList对象中(与上面相同)。

same like say 100's of student performing test. 就像说100的学生进行测试一样。 then what impact will be on questionList? 那么对questionList有什么影响? will it always need to instantiates? 它总是需要实例化吗? in commonField class? 在commonField类中? how to manage this? 如何处理呢? or due to static CLR will manage it ? 还是由于静态CLR会进行管理?

You should store common data in the Application object and the per-student data in Session . 您应该将通用数据存储在Application对象中,将每个学生的数据存储在Session

At some point, once per session: 在某个时间点,每个会话一次:

  Session["questions"] = CreateQuestionList();

and then whenever you need it: 然后在您需要时:

   questionList = (List<Question>)Session["questions"] ;

Your static variable is not reliable, won't scale to multiple servers and it certainly won't allow a different questionList for each student. 您的static变量不可靠,不会扩展到多个服务器,并且肯定不允许每个学生使用不同的questionList。

Being a static field, the 作为静态场,

questionList 问题清单

shall remain common for all students that are loggedIn. 对于所有已登录的学生来说应该保持通用。 So you must instantiate a new instance of QuestionsList for each student and store it in that student's session. 因此,您必须为每个学生实例化一个QuestionsList的新实例,并将其存储在该学生的会话中。

You need to put test id for user in the Session . 您需要在会话中输入用户的测试ID。 Do not try save object state between user requests in class fields or whatever. 不要尝试在类字段或任何其他用户请求之间保存对象状态。 Also you need to pay attention to the Cache ASP.NET object for quick access of last loaded questions for tests. 另外,您还需要注意Cache ASP.NET对象,以快速访问上一次加载的测试问题。

You should use Session instead of storing your questions in static fields. 您应该使用会话,而不是将问题存储在静态字段中。

List<Question> questionList=new List<Question>();
//fill the list with your questions
Session["Questions"] = questionList;

Then if you need questions of the current student use this: 然后,如果您需要当前学生的问题,请使用以下命令:

List<Question> questionList=(List<Question>)Session["Questions"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM