C# int.TryParse 方法


使用 C# 中的int.TryParse()方法將數字的字串表示形式轉換為整數。如果字串無法轉換,那麼int.TryParse()方法返回 false,即布林值。

假設你有數字的字串表示形式。

string myStr = "12";

現在使用int.TryParse()將其轉換為整數。它將得到轉換且返回 True。

int.TryParse(myStr, out a);

示例

 線上演示

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

輸出

String is a numeric representation: True

更新於: 02-Sep-2023

六萬四千多瀏覽量

開啟您的事業

完成課程獲得認證

立即開始
廣告
© . All rights reserved.