投放uint->双重无效? [英] Cast uint -> double invalid?
问题描述
在我创建的某些库中,我必须使用以下强制转换:
In some library I create I have to use following cast:
public void Foo(IList<uint> uintsList) // I need to use uint in the interface for this method
{
List<double> doublesList = uintsList.Cast<double>().ToList();
// Do something with the doublesList
}
我认为强制转换uint
-> double
应该始终有效,并且在我的测试过程中始终可以正常工作.
I assumed that cast uint
-> double
should be always valid, and during my test it always worked fine.
但是在使用此方法的应用程序中,出现了InvalidCastException
.不幸的是,我无权访问此应用程序.所以这是我的问题:
But in the application, which uses this method the InvalidCastException
occured. Unfortunately I do not have access to this application. So here are my questions:
- 什么可能导致此异常发生?强制转换uint-> double是否始终有效?
- 如何保护我的算法以避免这种异常?
编辑
当然,在强制转换之前,我总是执行检查以避免uintsList
为null或为空
EDIT
Of course, before casting I always perform check to avoid situation when uintsList
is null or empty
编辑2
好的,问题解决了,我使用ConvertAll
方法更改了强制类型转换,但我仍然不知道怎么发生?
因此,这个问题仍然困扰着我:同一部分代码如何在我的计算机上正常运行,而在另一个计算机上引发异常?不同的编译器/环境版本?一些特定的设置?谁能告诉我出于这种情况的原因我应该在哪里寻找避免将来发生的情况?
EDIT 2
OK, the problem is solved, I changed the cast using the ConvertAll
method, but still I don't understand how it could happen?
So this question still bothers me: how the same part of the code could run properly at my computer, and throw an exception at another? Different compiler/environment versions? Some specific settings? Can anyone tell me where should I seek for the reasons of this situation to avoid it in the future?
推荐答案
请参阅: C#转换列表< ; int>列出< double>
强制转换uint
-> double
是有效的,但是您要将uint列表转换为双精度列表.在大多数架构上,列表的大小甚至都不会相同(以字节为单位)-您将需要创建一个全新的列表并将每个元素分别转换.我会使用ConvertAll
:
The cast uint
-> double
is valid, but you are casting a list of uints to a list of doubles. On most architectures the lists won't even the same size (in bytes) - you will need to create an entirely new list and cast each element individually. I would use ConvertAll
:
List<double> doublesList = uintsList.ConvertAll(x => (double)x);
这篇关于投放uint->双重无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!