c# 在转换之前检测字符串是否为长或 DateTime
c# detect if the string is long or DateTime before converting
我有代码:
if(DateTime.TryParse(objString, out DateTime result))
{
// ...
}
else if (long.TryParse(objString, out long result))
{
// ...
}
else
{
// ...
}
如果 objString = "782,4" DateTime TryParse 没问题,结果我有 "782-04-01 00:00:00"
我该如何解决这个问题?
尝试指定文化:
DateTime.TryParse(objString, Thread.CurrentThread.CurrentCulture, System.Globalization.DateTimeStyles.None, out result)
最简单的解决方案就是简单地更改检查字符串的顺序。
所以代替:
if(DateTime.TryParse(objString, out DateTime result))
{
// ...
}
else if (long.TryParse(objString, out long result))
{
// ...
}
else
{
// ...
}
简单地说,更改 if
语句的顺序:
if (long.TryParse(objString, out long result))
{
// ...
}
else if (DateTime.TryParse(objString, out DateTime result))
{
// ...
}
else
{
// ...
}
正如我在评论中所说,如果要计算浮点数,则必须使用 double.TryParse
所以也许可以改用这个:
if (double.TryParse(objString, out double dblResult))
{
// ...
}
else if (DateTime.TryParse(objString, out DateTime dateTimeResult))
{
// ...
}
else
{
// ...
}
我有代码:
if(DateTime.TryParse(objString, out DateTime result))
{
// ...
}
else if (long.TryParse(objString, out long result))
{
// ...
}
else
{
// ...
}
如果 objString = "782,4" DateTime TryParse 没问题,结果我有 "782-04-01 00:00:00"
我该如何解决这个问题?
尝试指定文化:
DateTime.TryParse(objString, Thread.CurrentThread.CurrentCulture, System.Globalization.DateTimeStyles.None, out result)
最简单的解决方案就是简单地更改检查字符串的顺序。
所以代替:
if(DateTime.TryParse(objString, out DateTime result))
{
// ...
}
else if (long.TryParse(objString, out long result))
{
// ...
}
else
{
// ...
}
简单地说,更改 if
语句的顺序:
if (long.TryParse(objString, out long result))
{
// ...
}
else if (DateTime.TryParse(objString, out DateTime result))
{
// ...
}
else
{
// ...
}
正如我在评论中所说,如果要计算浮点数,则必须使用 double.TryParse
所以也许可以改用这个:
if (double.TryParse(objString, out double dblResult))
{
// ...
}
else if (DateTime.TryParse(objString, out DateTime dateTimeResult))
{
// ...
}
else
{
// ...
}