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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP