【发布时间】:2016-08-11 14:35:21
【问题描述】:
我想将字符串 (w.main.temp) 转换为整数。我正在使用以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace project1
{
interface IWeatherDataService
{
// public WeatherData GetWeatherData(Location location);
}
public class WeatherData
{
public string temp { get; set; }
}
public class Location
{
public string name { get; set; }
public string id { get; set; }
public WeatherData main { get; set; }
}
public class WeatherDataServiceException
{
}
class Program
{
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://api.openweathermap.org/data/2.5/weather");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string City = "ho chi minh";
string Key = "ca618d97e8b322c883af330b7f103f2d";
HttpResponseMessage response = await client.GetAsync("?q=" + City + "&APPID="+Key);
if(response.StatusCode == HttpStatusCode.OK)
{
Location w = response.Content.ReadAsAsync<Location>().Result;
int res = Convert.ToInt32(w.main.temp);
//Console.WriteLine(w.main.temp.GetType());
Console.WriteLine("id city: " + w.id);
Console.WriteLine("city: " + w.name);
Console.WriteLine("temperature: " + w.main.temp);
}
Console.ReadKey();
}
}
}
}
但是,它给了我一个错误:
输入字符串的格式不正确。
我需要进行哪些更改才能使代码正确地将string 转换为int?
【问题讨论】:
-
转换前
w.main.temp的内容是什么? -
检查
w.main.temp的值。很有可能它的格式确实不正确。特别注意逗号和小数点。 -
当我写 w.main.temp.GetType() 它写 System.String
-
@user3488862 我们知道它的类型,它的价值是什么。
Console.WriteLine(w.main.temp); -
304.15 但它是一个字符串,我需要将其转换为 int 因为它在开尔文中并且我需要它以度...
标签: c# string int type-conversion