开发者

Why does IsAssignableFrom() not work for int and double?

开发者 https://www.devze.com 2023-03-11 22:57 出处:网络
This is false: typeof(double).IsAssignableFrom(typeof(int)) This is false: typeo开发者_JAVA百科f(int).IsAssignableFrom(typeof(double))

This is false: typeof(double).IsAssignableFrom(typeof(int))

This is false: typeo开发者_JAVA百科f(int).IsAssignableFrom(typeof(double))

But this works:

double a = 1.0;
int b = 1;

a = b;

Clearly a double is assignable from an int but the framework IsAssignableFrom() gets it wrong.

Why? Or is this a bug in .NET caused by the special nature of int and double which have no inheritance relationship but are assignable (in one direction)?


C# is providing the implicit conversion from int to double. That's a language decision, not something which .NET will do for you... so from the .NET point of view, double isn't assignable from int.

(As an example of why this is language-specific, F# doesn't perform implicit conversions for you like this - you'd need to explicitly specify the conversion.)

It's worth looking at the documentation for Type.IsAssignableFrom (edited very slightly for readability):

Returns true if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c. Returns false if none of these conditions are true, or if c is null.

Now apply that to double and int and you'll see it should return false.

0

精彩评论

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

关注公众号