开发者

Cast uint -> double invalid?

开发者 https://www.devze.com 2022-12-21 23:24 出处:网络
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

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
}

I assumed that cast uint -> double should be always valid, and during my test it always worked fine.

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:

  • What could cause this exception occured? Isn't the cast uint->double always valid?
  • How can I secure my algorithm to avoid this exception?

EDIT

Of course, before casting I always perform check to avoid situation when uintsList is null or empty

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? Differ开发者_如何学Pythonent 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?


.Cast method is not meant to perform type conversion like that. It just performs conversions in the inheritance hierarchy.

The reason for this behavior is that the extension method signature takes an IEnumerable and not IEnumerable<T>. Consequently, getting the Current property of the enumerator returns an object to the Cast method. Of course, you can't unbox a value type of one type to another type directly. Basically, Cast will do something like:

int i = 42;
object o = i;
double d = (double)o; // fails.


See: C# Converting List<int> to List<double>

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号