如何在C#中将Object转换为List <string>?

Eri*_*Yin 4 c# asp.net list object

我有一个List<string>模型.当我编写一个html帮助器时,我可以从中获取数据metadata.Model,这是一个对象

// 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; }
Run Code Online (Sandbox Code Playgroud)

我的问题是:如何List<string>从一个Object

Kyl*_*man 13

如果object变量的基础类型是List<string>,则简单的强制转换将执行:

// throws exception if Model is not of type List<string>
List<string> myModel = (List<string>)Model; 
Run Code Online (Sandbox Code Playgroud)

要么

// return null if Model is not of type List<string>
List<string> myModel = Model as List<string>;
Run Code Online (Sandbox Code Playgroud)

  • 只是为了澄清,两个例子之间存在差异,如果转换不起作用,第一个将抛出异常,而第二个将仅向左操作数赋予"null". (3认同)
  • 你用我的答案更新后评论了一秒钟.:P (3认同)