2013-01-20 23 views

回答

2

您可以使用int.TryParse

int result = 0; 
bool success = int.TryParse("123", out result); 

這裏成功將成真,如果解析成功和fals其他明智和結果將解析詮釋值。

2

使用int.TryParse

int i; 
bool canBeParsed = int.TryParse("1847", out i); 
if(canBeParsed) 
{ 
    Console.Write("Number is: " + i); 
} 
2
var str = "18o2" 
int num = 0; 

bool canBeParsed = Int32.TryParse(str, out num); 
1

我一直在使用這些擴展方法多年。也許在開始時更復雜一些,但它們的使用非常簡單。您可以使用類似的模式擴展大部分簡單值類型,包括Int16,Int64,BooleanDateTime等。

using System; 

namespace MyLibrary 
{ 
    public static class StringExtensions 
    { 
     public static Int32? AsInt32(this string s) 
     { 
      Int32 result;  
      return Int32.TryParse(s, out result) ? result : (Int32?)null; 
     } 

     public static bool IsInt32(this string s) 
     { 
      return s.AsInt32().HasValue; 
     } 

     public static Int32 ToInt32(this string s) 
     { 
      return Int32.Parse(s); 
     } 
    } 
} 

要使用這些,只是包括MyLibraryusing聲明命名空間的列表。

"1847".IsInt32(); // true 
"18o2".IsInt32(); // false 

var a = "1847".AsInt32(); 
a.HasValue; //true 

var b = "18o2".AsInt32(); 
b.HasValue; // false; 

"18o2".ToInt32(); // with throw an exception since it can't be parsed. 
相關問題