string valueStr = " "; //"(123)-456-7890" or null or " " or "" or string.Empty or "abcdef"
int valueInt;
if (valueStr.Trim() != null || valueStr.Trim() != string.Empty || valueStr.Trim() != "")
{
//Perform regex routine to convert valueStr to valueInt and get only digits
}
else
{
valueInt = null;
}
我将数据插入SQL Db。我正在尝试将字母数字列{{n} varchar}清除为数字{int}。
但是,以上逻辑给我“ valueInt = null;”错误。部分。
Error = "Cannot convert null to int because it is a non-nullable value type"
如何确保代码仅对包含某些数据的行执行正则表达式功能,如果没有数据则给出null?
谢谢
更新:
string valueStr = " "; //"(123)-456-7890" or null or string.Empty or " " or "abcdef"
int? valueInt;
if (valueStr != null && valueStr.Trim() != "")
{
string pattern = string.Empty;
pattern = "[^0-9]";
Regex r = null;
r = new Regex(pattern, RegexOptions.Compiled);
try
{
valueInt = Convert.ToInt32(Regex.Replace(valueStr, pattern, string.Empty));
}
catch
{
valueInt = null;
}
Console.WriteLine(valueInt);
Console.ReadLine();
}
else
{
valueInt = null;
Console.WriteLine(valueInt);
Console.ReadLine();
}
最佳答案
定义您的valueInt
变量,如下所示:
int? valueInt;
然后可以将其分配为null。有关
Nullable types
的更多信息,请参见documentation