Я хочу преобразовать строку (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