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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9043773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:43:13  来源:igfitidea点击:

How to convert Object to List<string> in c#?

c#asp.netlistobject

提问by Eric Yin

I have a List<string>in Model. When I write a html helper, I can get the data from metadata.Model, which is an object

我有一个List<string>模型。当我编写一个html helper 时,我可以从中获取数据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; }

My question is: how to get List<string>from an Object?

我的问题是:如何List<string>Object?

采纳答案by Kyle Trauberman

If the underlying type of the objectvariable is List<string>, a simple cast will do:

如果object变量的基础类型是List<string>,一个简单的强制转换就可以了:

// throws exception if Model is not of type List<string>
List<string> myModel = (List<string>)Model; 

or

或者

// return null if Model is not of type List<string>
List<string> myModel = Model as List<string>;