2012-03-28 41 views
1

我開始開發一個C#/ ASP.net web應用程序,我在其中使用實體框架(Microsoft ORM)。C#/ ASP.net:List重新初始化莫名其妙

我的問題很簡單: 在我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); 
     } 
    } 
} 

而在我的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> 

結果,我有:

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

正如你所看到的,我的主題列表是莫名其妙地重新初始化顯示。 什麼是奇怪的是,我爲int的列表保存較爲完好,以及包含一個獨特的主題變量。

的主題類作爲與實體設計創建了,也許這是爲int的名單有什麼區別?

在此先感謝那些誰可以幫助我弄清楚發生了什麼那裏。 再見!

回答

3

您的Page_Load方法聲明瞭新的變量,稱爲lt。它不會爲實例變量分配任何內容,因爲局部變量正在映射實例變量。所以這個:

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

也許應該是這樣的:

lt = requete.ToList(); 

我也建議使用更有意義的變量名:)

+0

感謝! 很明顯,我不知道我怎麼沒有看到它^^ 對於變量名稱不用擔心,我打算這樣做,目前我只是試圖練習一點;) 再次感謝! – BPruvost 2012-03-28 09:23:08

0

您正在重新定義在Page_Load方法範圍變量;

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

改爲使用;

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