【问题标题】:Specified cast is not valid - List of double to list of float指定的强制转换无效 - 双精度列表到浮点列表
【发布时间】: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

标签: c# json list casting


【解决方案1】:

听起来你正在从object 转换为(类型),其中(类型)是floatdouble。这是一个拆箱操作,必须对正确的类型进行。该值,如object知道它是什么 - 如果您不正确地将其拆箱,则会引发此异常(警告:如果您将其拆箱为相同大小且兼容的东西,则会有一点回旋余地- 例如,您可以将 int-enum 拆箱为 int 和 vv)。

选项:

  • 坚持使用object,但要知道数据是什么并正确取消装箱 - 可能会在 取消装箱后强制转换,即float f = (float)(double)obj;(这里的(double) 是来自object 的取消装箱到double(float) 是从doublefloat 的类型转换)
  • 测试对象类型/使用Convert.ToSingle
  • 首先将属性更改为定义类型,而不是object

完整示例:

List<object> actuallyDoubles = new List<object>{ 1.0, 2.0, 3.0 };
List<double> doubleDirect = actuallyDoubles.ConvertAll(x => (double)x); // works
// List<float> floatDirect = actuallyDoubles.ConvertAll(x => (float)x); // fails per question
List<float> floatViaDouble = actuallyDoubles.ConvertAll(x => (float)(double)x); // works
List<float> floatViaConvert = actuallyDoubles.ConvertAll(x => Convert.ToSingle(x)); // works

【讨论】:

  • @Andrew 我在下面添加了更多示例
猜你喜欢
  • 1970-01-01
  • 2015-08-21
  • 2015-01-16
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
  • 2020-06-16
相关资源
最近更新 更多