2012-01-28 61 views
2

我在Model中有一個List<string>。 當我寫一個HTML輔助,我可以從metadata.Model獲取數據,這是一個對象如何將對象轉換爲列表<string>在C#中?

// this is from MVC3 (namespace System.Web.Mvc -> ModelMetadata), I did not write this 
// Summary: 
//  Gets the value of the model. 
// 
// Returns: 
//  The value of the model. For more information about System.Web.Mvc.ModelMetadata, 
//  see the entry ASP.NET MVC 2 Templates, Part 2: ModelMetadata on Brad Wilson's 
//  blog 
public object Model { get; set; } 

我的問題是:如何從一個ObjectList<string>

+2

什麼是對象的實際類型?將_any_對象轉換爲某些字符串列表是沒有意義的。 – 2012-01-28 07:53:48

+2

你是說typecast? obj as List ? – zmbq 2012-01-28 07:53:50

回答

8

如果底層類型object變量是List<string>,一個簡單的投會做:

// throws exception if Model is not of type List<string> 
List<string> myModel = (List<string>)Model; 

// return null if Model is not of type List<string> 
List<string> myModel = Model as List<string>; 
+3

爲了澄清,這兩個例子之間有一個區別,第一個會拋出一個異常,如果轉換不起作用,而第二個只會將'null'分配給左操作數。 – annonymously 2012-01-28 07:55:28

+3

在我更新我的答案後,你評論了一秒。 :P – 2012-01-28 07:56:59

+0

哦,謝謝,這個工程。我被這個線程誤導http://stackoverflow.com/questions/632570/cast-received-object-to-a-listobject-or-ienumerableobject :(並嘗試各種複雜的xxx。 – 2012-01-28 07:57:20

相關問題