简体   繁体   English

指定的类型转换无效-浮点数列表的双精度数列表

[英]Specified cast is not valid - List of double to list of float

So I store a list of float in a JSON file, this is what the JSON list looks like: 所以我将float列表存储在JSON文件中,这就是JSON列表的样子:

"RollSize": "[17.5,18.0,19.0,23.5,26.5,35.0,35.5,38.0]"

I use a method which returns a list of objects as there are multiple lists to return. 我使用一种返回对象列表的方法,因为有多个列表要返回。 I then cast the list of objects to a float. 然后,我将对象列表转换为浮点型。 However the Specified cast is not valid receive an exception when doing this. 但是,执行此操作时Specified cast is not valid But if I cast the list of objects to a double it works. 但是,如果我将对象列表转换为两倍,则可以使用。 Here is the two methods: 这是两种方法:

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));
            }
        }

Repository method: 存储库方法:

 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.");
            }
        }

However I noticed that if I looped around the list in a foreach I could cast each value to a float. 但是我注意到,如果我在foreach中遍历列表,则可以将每个值都转换为浮点数。 So I'm not sure what's going on here. 所以我不确定这是怎么回事。

Anyone know? 有人知道吗

It sounds like you're cast is casting from object to (the type), where (the type) is either float or double . 听起来您正在将objectobject投射到(类型),其中(类型)是floatdouble This is an unboxing operation, and must be done to the right type . 这是拆箱操作,必须对正确的类型进行 The value, as object , knows what it is - and this exception is thrown if you unbox it incorrectly (caveat: there is a little wriggle room if you unbox it to something the same size and compatible - for example you can unbox an int-enum to an int and vv). 该值(作为object知道它的含义 -如果您未正确将其拆箱,则会抛出此异常(警告:如果将其拆箱为相同大小且兼容的东西,则会有一点蠕动空间-例如,您可以将int-枚举为int和vv)。

Options: 选项:

  • stick with object , but know what the data is and unbox it correctly - perhaps casting after the unbox, ie float f = (float)(double)obj; 坚持object ,但知道数据是什么,并正确地取消装箱-也许取消装箱进行转换,即float f = (float)(double)obj; (the (double) here is the unbox from object to double ; the (float) is the type conversion from double to float ) (这里的(double)是从objectdouble的取消框; (float)是从doublefloat的类型转换)
  • test the object type / use Convert.ToSingle 测试对象类型/使用Convert.ToSingle
  • change the property to be a defined type in the first place, rather than object 首先将属性更改为定义的类型,而不是object

Full examples: 完整示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM