我有代码:
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"
我该如何解决这个问题?
最佳答案
最简单的解决方案是简单地更改检查字符串的顺序。
所以代替:
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
{
// ...
}
正如我在评论中所说,如果你想计算 float ,你必须使用 double.TryParse
所以也许可以改用这个:
if (double.TryParse(objString, out double dblResult))
{
// ...
}
else if (DateTime.TryParse(objString, out DateTime dateTimeResult))
{
// ...
}
else
{
// ...
}
关于c# 在转换之前检测字符串是否为长或 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52739816/