【问题标题】:How to convert Object to List<string> in c#?如何在 C# 中将 Object 转换为 List<string>?
【发布时间】:2012-02-21 01:27:30
【问题描述】:

我在模型中有一个List&lt;string&gt;。 当我写一个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; }

我的问题是:如何从Object 获取List&lt;string&gt;

【问题讨论】:

  • 对象的实际类型是什么?将 any 对象“转换”为某个字符串列表是没有意义的。
  • 你是说类型转换? obj as List ?

标签: c# asp.net list object


【解决方案1】:

如果object 变量的基础类型是List&lt;string&gt;,则可以进行简单的转换:

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

【讨论】:

  • 澄清一下,这两个示例之间存在差异,如果强制转换不起作用,第一个示例将抛出异常,而第二个示例仅将 null 分配给左侧操作数。
  • 你在我更新我的答案后评论了一秒钟。 :P
  • 哦,谢谢,这行得通。我被这个线程stackoverflow.com/questions/632570/…误导了:(并尝试了各种复杂的xxx。
猜你喜欢
  • 2018-12-27
  • 1970-01-01
  • 2020-11-27
  • 1970-01-01
  • 2021-08-08
  • 1970-01-01
  • 2018-11-23
  • 1970-01-01
相关资源
最近更新 更多