111,126
社区成员
发帖
与我相关
我的任务
分享string str = "5";
int? v = int.Parse(str);
:
using System;
public static class Program
{
public static void Main()
{
string str = null;// null
Nullable<int> intStr = str.ToNullableInteger();
string str1 = string.Empty;// 空字符串
Nullable<int> intStr1 = str1.ToNullableInteger();
string str2 = " ";// 空格字符串
Nullable<int> intStr2 = str2.ToNullableInteger();
string str3 = "abc";// 非数字
Nullable<int> intStr3 = str3.ToNullableInteger();
string str4 = "3434";// 符合的数字
Nullable<int> intStr4 = str4.ToNullableInteger();
string str5 = "3432353745348583068506835083405304853454";// 超出范围的数字
Nullable<int> intStr5 = str5.ToNullableInteger();
Console.WriteLine("intStr:{0}", intStr.HasValue ? intStr.Value.ToString() : "null");
Console.WriteLine("intStr1:{0}", intStr1.HasValue ? intStr1.Value.ToString() : "null");
Console.WriteLine("intStr2:{0}", intStr2.HasValue ? intStr2.Value.ToString() : "null");
Console.WriteLine("intStr3:{0}", intStr3.HasValue ? intStr3.Value.ToString() : "null");
Console.WriteLine("intStr4:{0}", intStr4.HasValue ? intStr4.Value.ToString() : "null");
Console.WriteLine("intStr5:{0}", intStr5.HasValue ? intStr5.Value.ToString() : "null");
Console.ReadKey();
}
/// <summary>
/// 扩展方法,将字符串转化为可以为null的整型
/// </summary>
/// <param name="str">要转化的字符串</param>
/// <returns>可以为null的整型</returns>
public static Nullable<int> ToNullableInteger(this string str)
{
if (!string.IsNullOrWhiteSpace(str))
{
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^\d+$");// 匹配数字正则表达式
if (regex.IsMatch(str))
{
int integer;
if (int.TryParse(str, out integer))// 尝试转换,防止超出范围
return new Nullable<int>(integer);// 转换成功,则将值赋给Nullable<int>构造方法
}
}
return null;// 其余一切情况均返回null
}
}
// 输出结果
// intStr:null
// intStr1:null
// intStr2:null
// intStr3:3434
// intStr4:null
Convert.ToInt32();