【发布时间】:2017-11-28 04:45:34
【问题描述】:
所以我在 JSON 文件中存储了一个浮点列表,这就是 JSON 列表的样子:
"RollSize": "[17.5,18.0,19.0,23.5,26.5,35.0,35.5,38.0]"
我使用一种返回对象列表的方法,因为要返回多个列表。然后我将对象列表转换为浮点数。但是,Specified cast is not valid 在执行此操作时会收到异常。但是,如果我将对象列表转换为双精度,它就可以工作。这是两种方法:
private void DisplayCutOffs(object sender, EventArgs e) {
try {
// Errors here unless I cast to double
_view.CurrentCutOffValues = _systemVariablesManager.ReturnListBoxValues("CutOff").Cast<float>().ToList();
}
catch (Exception ex) {
LogErrorToView(this, new ErrorEventArgs(ex.Message));
}
}
存储库方法:
public List<object> ReturnListBoxValues(string propertyName) {
if (File.Exists(expectedFilePath)) {
var currentJsonInFile = JObject.Parse(File.ReadAllText(expectedFilePath));
return JsonConvert.DeserializeObject<List<object>>(currentJsonInFile["SystemVariables"][propertyName].ToString());
}
else {
throw new Exception("Setup file not located. Please run the Inital Set up application. Please ask Andrew for more information.");
}
}
但是我注意到,如果我在 foreach 中循环列表,我可以将每个值转换为浮点数。所以我不确定这里发生了什么。
有人知道吗?
【问题讨论】:
-
"[17.5,18.0,19.0,23.5,26.5,35.0,35.5,38.0]"那是字符串而不是数组。 -
你是对的,但它会解析成一个对象列表
-
double 是 8 个字节,而 float 是 4 个字节。 Linq 通常会生成一个可以转换为任何类型的通用列表对象,但不会将一种类型转换为另一种类型,除非它是显式的。
-
@jdweng 所以我的演员阵容是隐含的?
-
是的。您正在使用 .ToList() ,它采用 Linq 集合并转换为 List