为什么数据类型转换< long oldTimestamp = Convert.ToInt64(values)>返回错误?团结c#

时间:2016-07-16 04:36:18

标签: c# unity3d

运行此脚本时出错:

long timestamp = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;
string values = PlayerPrefs.GetString("margaretSellTimer1");
long oldTimestamp = Convert.ToInt64(values);
long elapsedSeconds = Convert.ToInt64(timestamp) - oldTimestamp;

string value = PlayerPrefs.GetString("margaretSellTimer");
long oldTickTime = Convert.ToInt64(value);
oldTickTime = oldTickTime + elapsedSeconds;

该行:

long timestamp = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;

返回错误:

Assets/script/margaretSellTimer.cs(138,22): error CS0266: Cannot implicitly convert type double to long. An explicit conversion exists (are you missing a cast?)

该行:

long oldTimestamp = Convert.ToInt64(values);

返回错误:

Input string was not in the correct format

为什么这是一个错误?我做了一个转换器。

谢谢

2 个答案:

答案 0 :(得分:2)

错误告诉您TotalSecondsdouble而不是long。只需将long timestamp替换为double timestamp

double timestamp = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;

或者将double转换为long(长)。

long timestamp = (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;

您也可以按照Jeppe在评论中提到的方式执行此操作,以防止不必要的数据类型转换。

long timestamp = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).Ticks / TimeSpan.TicksPerSecond;

答案 1 :(得分:0)

对于你的施法错误:

如果您查看TimeSpan class的文档,您会发现TimeSpan.TotalSecondsdouble。并且c#不允许隐式转换为long。因此,您要么将时间戳的数据类型更改为double timestamp,要么显式转换。

long timestamp = (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;

您的转化错误:

value = PlayerPrefs.GetString("margaretSellTimer")的结果是无法解析为long的结果,因为它包含非法字符,或者它可能是双重字符。在转换行中创建一个断点并检查value的内容。