如何将字符串转换为int c#

use*_*862 1 c# string int type-conversion

我想将string(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();
            } 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,它给了我一个错误:

输入字符串的格式不正确.

为了使代码正确转换string,我需要更改int什么?

M.S*_*.S. 5

简单地使用 int.TryParse(string, out int parameter)

int res = 0;
bool parseSuccessful = int.TryParse(w.main.temp, out res);

//int.TryParse() returns a bool value to indicate whether parsing is Successful  or not.
Run Code Online (Sandbox Code Playgroud)

如果要解析剩下的数字 .

例如

 w.main.temp = "123.45";
Run Code Online (Sandbox Code Playgroud)

你想输出int123.然后使用以下代码

if (w.main.temp.IndexOf(".") >= 0)
{
    parseSuccessful = int.TryParse(w.main.temp.Substring(0, w.main.temp.IndexOf(".")), out res);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您要使用`int.TryParse`,您应该捕获返回值以了解它是否失败或将其放在`if`语句中.它也可以处理一个`null`字符串(将返回`false`).最后,如果字符串实际上不是有效的整数值,那么`int.TryParse`将不会更好. (2认同)