为什么IsAssignableFrom()不是为int和double工作? [英] Why does IsAssignableFrom() not work for int and double?
问题描述
这是错误的: typeof运算(双).IsAssignableFrom(typeof运算(INT))
这是错误的: typeof运算(INT).IsAssignableFrom(typeof运算(双))
不过,这部作品:
double a = 1.0;
int b = 1;
a = b;
显然双
是从分配 INT
,但该框架 IsAssignableFrom()
得到它错了。
Clearly a double
is assignable from an int
but the framework IsAssignableFrom()
gets it wrong.
为什么呢?或者这是由INT的特殊性和双重它们没有继承关系,但分配(在一个方向)?
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#是提供从 INT
隐式转换为双
。这是一个的语言的决定,而不是一些东西,.NET会为你做......所以从在.NET点,双
的是不是的分配由 INT
。
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
.
(截至为什么这是特定于语言的一个例子,F#的不的执行隐式转换为你这个样子 - 你需要显式地指定转换)
(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.)
这是值得看的文档<一href="http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx"><$c$c>Type.IsAssignableFrom$c$c> (编辑非常轻微的可读性):
It's worth looking at the documentation for Type.IsAssignableFrom
(edited very slightly for readability):
返回true,如果c和电流型重present相同的类型,或者如果当前类型是C的继承层次结构,或者如果当前类型是一个接口,ç工具,或者如果c是一个泛型类型参数和当前的类型再presents的C的制约因素之一。返回false如果这些条件都为真,或者c为null。
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.
现在它应用到双
和 INT
键,你会看到它的应该的返回false。
Now apply that to double
and int
and you'll see it should return false.
这篇关于为什么IsAssignableFrom()不是为int和double工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!