【问题标题】:Would it be possible to convert between data types using a string?是否可以使用字符串在数据类型之间进行转换?
【发布时间】:2018-05-30 12:20:48
【问题描述】:

是否可以使用字符串在数据类型之间进行转换?我正在编写一个接收以下 JSON 的 Azure 函数:

{
  "data": "1",
  "type": "int"
}

我想将“1”返回为 int。到目前为止我做了什么:

dynamic body = await req.Content.ReadAsStringAsync();
Data data = JsonConvert.DeserializeObject<Data>(body as string);

数据类:

public class Data
{
    public string data { get; set; },
    public string type { get; set; }
}

谢谢。

【问题讨论】:

  • 你不需要dynamicReadAsStringAsync返回一个字符串。
  • 谢谢,我不知道。
  • 为什么投反对票?
  • 不是我,我不知道为什么是 DV。不过有一个提示,我建议您不要使用“数据”来命名所有内容,也不要使用“类型”。
  • 谢谢,我会改改以提高o/的可读性。

标签: c# .net azure types


【解决方案1】:

在您的 "type" 中,您应该使用完全限定的 .net 类型名称:

例子:

System.Int32

一旦你有了这个,使用下面的方式将它转换成Type

Data data = JsonConvert.DeserializeObject<Data>(body as string);    
Type myType = Type.GetType(data.type);
var item = Convert.ChangeType(data.data, myType);
Console.WriteLine(item);
Console.WriteLine(item.GetType());

【讨论】:

  • 但这不会总是得到字符串,因为 data.type 总是一个字符串吗?
  • data.type = "System.Int32" 时,item 将是Int32 类型。发布前测试了代码
  • 对不起,我在用手机。当我回到家时,我会测试并接受你的答案。
猜你喜欢
  • 2012-10-28
  • 2017-08-25
  • 1970-01-01
  • 1970-01-01
  • 2017-07-02
  • 2012-01-16
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多