[C#] 卡了一天的問題... EntitySet 轉 IList 型別失敗的解法...

  • 9223
  • 0

摘要:[C#] 卡了一天的問題... EntitySet 轉 IList 型別失敗的解法...

 最近開始學習 SilverLight,很多.Net 慣用的做法,都得另尋他法,最近遇到了個怪怪的問題在此將他記錄下來。

 

一開始由於需要對 ListBox 的 Item 做新增及移除的功能,但 ListBox 的 ItemsSource為 EntitySet 型別,於是就想將其型別轉為 IList 來達成新增及移除的需求。

於是就寫了這樣的語法:

 

ItemsControl box = e.Options.Destination as ItemsControl;
IList<ClassA> itemsSource = box.ItemsSource as  IList<ClassA>;

 

雖然編譯上沒有錯誤,原為以為會取得一 實作 IList 介面 Item 型別為 ClassA 的 box.ItemsSource 集合,但是由於轉型失敗,使得 itemsSource 的值為 Null,這與原本的期待不符...

 

後來上網查詢了一翻之後得到了這個答案:
"Neither EntityList<T> nor EntityCollection<T> implement this interface. It wouldn’t make sense either, since EntityList and EntityCollection don’t really work in an index-oriented fashion and IList is index-centric." - Jeff Handley - MS WCF RIA Service team.

 

看來是無望了,正想另尋途徑時,又突然有了新的想法,語法如下:

 

ItemsControl box = e.Options.Destination as ItemsControl;

IList<ClassA> itemsSource = (box.ItemsSource as IEnumerable<ClassA>).ToList<ClassA>() as IList<ClassA>;

 

想不到這一試反倒讓我成功了,只是多轉了2次型別...總覺得應該有更好的解法...

 

 

參考資源:

 

Why EntitySet<T> not implement IList<T>?>:前往說明頁面

Add/Remove with DataForm and RIA Services:前往說明頁面

 

MSDN 上的說明:

EntitySet 類別:前往說明頁面

IList 介面:前往說明頁面


Cross

推到 Plurk! 分享