【问题标题】:Convert C# Hashtable value to List [duplicate]将 C# Hashtable 值转换为 List [重复]
【发布时间】:2015-12-02 15:56:50
【问题描述】:

我正在从 Javascript 向 C# 发送一个发布请求

Javascript

var name = "doe";
var ids = [1,2,3];

var parameter = {
ids : ids,
name : name,
groups: groups
}

C#

public string sampleMethod (Hashtable hashtable)
{
string name = hashtable["name"].toString();//works well
List<long> ids = (List<long>)hashtable["ids"];//doesnt work
}

我只想从 hashtable["ids"] 中获取值 [1,2,3] 然后将其转换为 long;

【问题讨论】:

  • 我认为 long 不能直接转换,因此需要先转换 (List&lt;long&gt;) Convert.ToLong(hashtable["ids"]) 这个 sorf 的东西
  • 您确定javascript值[1, 2, 3]表示为List&lt;long&gt;吗?我建议它表示为数组 - 可能是 int 而不是 long。
  • 同意@wudzik 问题和解决方法基本一样。
  • @wudzik 这根本不是重复的。他正在尝试转换哈希表的值,而不是键。
  • @user3770093 尝试hashtable["ids"].GetType() 以获取存储在哈希表中的类型的提示。也许在那之后你就知道要投射什么类型了。

标签: c# json post casting hashtable


【解决方案1】:

试试这个..

 Array ids = (Array)hashtable["ids"];

List<int> ids = (List<int>)hashtable["ids"]; 

 int[] ids = (int[])hashtable["ids"];

【讨论】:

  • 无法将类型为“Newtonsoft.Json.Linq.JArray”的对象转换为类型“System.Collections.Generic.List`1[System.Int32]”。我想我不能简单地转换它,我目前正在尝试进行一些反序列化。
  • @user3770093 你已经知道类型了吗?投射到它并致电ToObject&lt;List&lt;in&gt;&gt;()
猜你喜欢
  • 1970-01-01
  • 2013-01-07
  • 2014-08-14
  • 2010-09-15
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多