摘要:[.net]快速檢查變數是否為數字,快速轉換型態
vb有內建isNumeric可檢查變數是否為數字,但C#沒有,c#使用者可自行加上下列函數(微軟提供),即可使用isNumeric
// IsNumeric Function
// 資料來源:http://support.microsoft.com/kb/329488/zh-tw
public static bool IsNumeric(object Expression)
{
// Variable to collect the Return value of the TryParse method.
bool isNum;
// Define variable to collect out parameter of the TryParse method. If the conversion fails, the out parameter is zero.
double retNum;
// The TryParse method converts a string in a specified style and culture-specific format to its double-precision floating point number equivalent.
// The TryParse method does not generate an exception if the conversion fails. If the conversion passes, True is returned. If it does not, False is returned.
isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
return isNum;
}
一般在轉換型態的時候,都要用諸如Convert.ToInt32()(這是C#), CInt()(這是VB)之類的語法,但是此類語法如果你沒有先檢查是否為數字
直接馬上就轉型的話,萬一變數不為數字,那就會出現exception,這裡介紹建議方便轉型的函式庫Vici, 透過visual studio 的nuget就可直接安裝
即使是錯誤的轉型,例如把字串abcd轉成int,也不會出現exception, 而是return 0(p.s此為方便用,若要嚴格監控變數狀態請勿使用vici轉型)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Vici.Core;
namespace ViciTest
{
class Program
{
static void Main(string[] args)
{
string var1 = "789789";
Console.WriteLine(var1.Convert());
Console.ReadKey();
}
}
}