如何将对象转换为列表<;字符串>;在c#中?
我在模型中有一个如何将对象转换为列表<;字符串>;在c#中?,c#,asp.net,list,object,C#,Asp.net,List,Object,我在模型中有一个列表。 当我编写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 inform
列表
。
当我编写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; }
我的问题是:如何从
对象
获取列表
?如果对象
变量的基础类型是列表
,则简单的强制转换即可:
// throws exception if Model is not of type List<string>
List<string> myModel = (List<string>)Model;
//如果模型不是列表类型,则引发异常
List myModel=(List)模型;
或
//如果模型不是列表类型,则返回null
列表myModel=模型为列表;
对象的实际类型是什么?将任何对象“转换”为字符串列表是没有意义的。你是说类型转换?obj as List?为了澄清,这两个示例之间存在差异,第一个示例在强制转换不起作用时会引发异常,而第二个示例只会将null
赋值给左操作数。在我用该值更新答案后,您评论了第二个示例:波赫,谢谢,这很有效。我被这条线索误导了,尝试了各种复杂的方法。
// return null if Model is not of type List<string>
List<string> myModel = Model as List<string>;