2012-01-28 11 views
2

モデルにはList<string>があります。オブジェクトオブジェクトをリストに変換するには<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; } 

ある 私はHTMLヘルパーを書くとき、私はmetadata.Modelからデータを取得することができますが、私の質問は:ObjectからList<string>を取得する方法?

+2

オブジェクトの実際の型は何ですか? _any_オブジェクトをいくつかの文字列リストに "変換"することは意味がありません。 –

+2

タイプキャストを意味しますか? objをList としますか? – zmbq

答えて

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

明確にするために、2つの例の違いがあります。キャストが機能しない場合、最初の例外は例外をスローしますが、2番目の例外は左のオペランドに 'null 'を割り当てます。 – annonymously

+3

私はその答えを更新した後、1秒間コメントしました。 :P –

+0

オハイオ州、ありがとう、これは動作します。私はこのスレッドによって誤解されましたhttp://stackoverflow.com/questions/632570/cast-received-object-to-a-listobject-or-ienumerableobject :(そして複雑なxxxのすべての種類を試しました。 –

関連する問題