简体   繁体   English

C#/ ASP.net:列表重新初始化莫名其妙

[英]C#/ASP.net : List reinitialized inexplicably

I'm starting the development of a C#/ASP.net web app, within which I use the Entity Framework (Microsoft ORM). 我正在开始开发一个C#/ ASP.net网络应用程序,我在其中使用实体框架(Microsoft ORM)。

My problem is very simple : In my default.aspx.cs I have this : 我的问题很简单:在我的default.aspx.cs中我有这个:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace Projet___TestConnaissances
{
    public partial class _Default : System.Web.UI.Page
    {
        protected List<Theme> lt = new List<Theme>();
        protected List<int> li = new List<int>();
        protected Theme th = new Theme();
        protected String test = "teeeest";
        protected int v = 1;

        protected void Page_Load(object sender, EventArgs e)
        {
            DataSourceContainer bdd = new DataSourceContainer();
            var requete = from Theme in bdd.ThemeSet select Theme;
            List<Theme> lt = requete.ToList(); // gets a list of themes
            v = lt.Count(); // puts in v the number of themes in lt
            th = lt.First(); // variable containing a unique theme (first of lt)
            test = "Ceci est un test";
            li.Add(1);
            li.Add(2);
            li.Add(3);
        }
    }
}

And in my default.aspx, I display this : 在我的default.aspx中,我显示了这个:

<p>
<br />test : <%= test %>
<br />v :  <%= v %>
<br />th.libelle : <%= th.libelle %>
<br />lt.count : <%= lt.Count() %>
<br />li.count : <%= li.Count() %>
</p>

As a result, I have : 结果,我有:

test : Ceci est un test
v : 3
th.libelle : Test ajout libelle
lt.count : 0
li.count : 3

As you can see, my List of Theme is inexplicably reinitialized before its displayed. 正如你所看到的,我的主题列表在显示之前被莫名其妙地重新初始化。 What is weird is that my List of int is well kept, as well as the variable containing a unique theme. 奇怪的是我的int列表得到了很好的保存,以及包含唯一主题的变量。

The Theme class as been created with the Entity Designer, maybe this is the difference with the List of int ? 使用实体设计器创建的Theme类,也许这与int的列表有什么不同?

Thanks in advance to those who will help me figure out what's happening there. 在此先感谢那些能帮助我弄清楚那里发生了什么的人。 Bye ! 再见!

Your Page_Load method is declaring a new variable called lt . 您的Page_Load方法声明了一个名为lt变量。 It's not assigning anything to the instance variable, because the local variable is shadowing the instance variable. 它没有为实例变量赋值,因为局部变量正在遮蔽实例变量。 So this: 所以这:

List<Theme> lt = requete.ToList();

should probably be this: 应该是这样的:

lt = requete.ToList();

I'd also suggest using more meaningful variable names :) 我还建议使用更有意义的变量名:)

You are redefining variable in method scope in page_load; 您正在重新定义page_load中方法范围中的变量;

List<Theme> lt = requete.ToList(); // gets a list of themes

instead use; 改为使用;

lt = requete.ToList(); // gets a list of themes

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

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