2011-08-10 32 views
0
的變量進行操作

這裏是我正在嘗試工作。foreach語句不能對類型爲

List<MasterEmployee > masterEmployee = new List<MasterEmployee >(); 
masterEmployee = MasterEmployee.GetAll("123"); //connecting db and returning a list... 


    foreach (MasterEmployee item in masterEmployee) 
    { 
     foreach (Registration reg in item.Registration) //<<<error here... 
     { 
      // 
     } 
    } 

錯誤的位置:

Error 2 foreach statement cannot operate on variables of type Registration because Registration does not contain a public definition for 'GetEnumerator' 

我有一個名爲MasterEmployee類,並在它我有一個很少的道具和一些方法就可以了

[Serializable] 
    public class MasterEmployee 
    { 

     //few props omitted .... 

     protected Registration _registration; 
     [CopyConstructorIgnore] 
     public Registration Registration 
     { 
      get 
      { 
       return _registration; 

      } 
      set 
      { 
       this._registration = value; 
      } 
     } 
     protected User _user; 
     [CopyConstructorIgnore] 
     public User MyUser 
     { 
      get 
      { 
       return _user; 
      } 
      set 
      { 
       this._user= value; 
      } 
     } 

     protected Student _student; 
     [CopyConstructorIgnore] 
     public Student Student 
     { 
      get 
      { 
       return _student; 
      } 
      set 
      { 
       this._student = value; 
      } 
     } 
} 

回答

3

在錯誤消息中所提供的說明是清楚。您正試圖迭代item.Registration,這是Registration的一個實例。但是,Registration不是從可迭代類型派生的,並且不實現自定義迭代類型所需的GetEnumerator函數。所以它不能用foreach循環迭代。

但我相信你的命名約定是不正確的,或者你誤解了你的數據模型。爲什麼Registration實例會包含一個Registration實例的集合?如果一個項目可以有多個與之關聯的Registration實例,那麼該屬性應該被稱爲類似於item.Registrations,並且它不應該是Registration類型,它應該是列表/集合類型,其中包含Registration實例。

+0

那麼最新的解決方案是什麼? –

+0

@阿布 - 首先澄清你想要做什麼,然後從那裏開始。正如我所指出的,我真的不認爲你實際上希望'Registration'是一個包含'Registration'實例列表的可迭代類。你可能想要使用類似'ArrayList'的東西,並將你的'Registration'實例放在那裏。然後你迭代* list *,而不是'Registration'。 – aroth

+0

你有沒有看過數據模型類的禮儀,所以我想要實現的是如何迭代列表......這就是註冊...學生......等等...... –

1
+0

那麼沒有其他方式實現IEnumerable? –

+0

這不是什麼大不了的事。只需將您的類的聲明更改爲:「public class MasterEmployee:IEnumarable」並添加一個函數public IEnumerator GetEnumerator(){} –

+0

對不起,我遲到了,我越來越累了;)類MasterEmployee不是問題,類註冊是不是Collection類。雖然我沒有看到這一點,但是爲什麼你在那裏做第二個foreach,這只是一個單一的值。儘管如此,類註冊不在codesnippet中。 –

相關問題