我想將字符串(w.main.temp
)轉換爲整數。我使用下面的代碼:如何將字符串轉換爲int c#
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();
}
}
}
}
但是,它給我一個錯誤:
Input string was not in a correct format.
我需要什麼,以便代碼將string
轉換爲int
正確的改變?
在轉換之前'w.main.temp'的內容是什麼? –
檢查'w.main.temp'的值。相當好的機會是它確實格式不正確。請特別注意逗號和小數點。 – dasblinkenlight
當我寫w.main.temp.GetType()它寫入System.String – user3488862