Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将对象转换为列表<;字符串>;在c#中?_C#_Asp.net_List_Object - Fatal编程技术网

如何将对象转换为列表<;字符串>;在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>;