C# int.Parse Vs int.TryParse 方法


使用 int.TryParse 和 intParse 方法在 C# 中將字串表示的數字轉換為整數。

如果字串不能被轉換,則 int.TryParse 方法返回 false,即一個布林值,而 int.Parse 返回一個異常。

我們來看一個 int.Parse 方法的示例 −

示例

 線上演示

using System.IO;
using System;
class Program {
   static void Main() {
      int res;
      string myStr = "120";
      res = int.Parse(myStr);
      Console.WriteLine("String is a numeric representation: "+res);
   }
}

輸出

String is a numeric representation: 120

我們來看一個 int.TryParse 方法的示例。

示例

 線上演示

using System.IO;
using System;
class Program {
   static void Main() {
      bool res;
      int a;
      string myStr = "120";
      res = int.TryParse(myStr, out a);
      Console.WriteLine("String is a numeric representation: "+res);
   }
}

輸出

String is a numeric representation: True

更新於: 2020 年 6 月 22 日

4k + 瀏覽

開啟你的 職業

完成課程認證

開始
廣告
© . All rights reserved.