the methods of that string convert to int
想要把 數字string 轉成int有幾種作法?可使用 int.Parse、int.TryParse、Convert.ToInt32
三種方法,如下範例
using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a;
            a = int.Parse("123");
            Console.WriteLine("a={0}", a);
            int b;
            string bb = "456";
            bool result = int.TryParse(bb, out b);
            Console.WriteLine("{0}, b={1}", result == true ? "succes" : "fail", b);
            int c;
            c = Convert.ToInt32("789");
            Console.WriteLine("c={0}", c);
            //int d;
            //string dd = "111";
            //d = dd as int;
            //Console.WriteLine("d={0}", d);
            //int e;
            //string ee = "456";
            //e = (int)ee;
            //Console.WriteLine("e={0}", e);
            Console.ReadKey();
        }
    }
}
說明:
可以成功轉換的方法就不多說明了,看範例就可以自行應用了。
來看程式不能跑的地方,例如
dd as int;
其出現的錯誤為
「CS0039 The as operator must be used with a reference type or nullable type ('int' is a non-nullable value type)」
關鍵字「as」是專門用來把一類別嘗試轉成另一型別,
所以用關鍵字「as」想來把 string 轉成是 int 是不行的。
另外一種想使用明確轉換(Explicit Conversions)的方式來將 string 轉成 int 也是不行的
string ee = "456";
e = (int)ee;
出現的錯誤訊息為「CS0030 Cannot convert type 'string' to 'int'」
參考資料:
Int32.TryParse 方法 (String, NumberStyles, IFormatProvider, Int32)