如何在c#中将对象转换为List<string>?

11

我在Model中有一个List<string>。当我编写html helper时,我可以从metadata.Model获取数据,该对象是一个List<string>

// 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; }

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


2
对象的实际类型是什么?将“任何”对象转换为一些字符串列表是没有意义的。 - Jeff Mercado
2
你是指类型转换吗?将 obj 转换为 List<string> 类型? - zmbq
1个回答

27
如果 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>;

4
仅澄清一下,这两个示例之间有区别,第一个示例如果强制转换不起作用将会抛出异常,而第二个示例只会将null赋值给左操作数。 - annonymously
3
你在我更新答案后一秒钟就评论了那个。 :P - Kyle Trauberman
哦,谢谢,这个可以用。我被这个主题误导了https://dev59.com/VHRB5IYBdhLWcg3wa2m2 :(,并尝试了各种复杂的xxx。 - Eric Yin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接