为什么IsAssignableFrom()不是为int和double工作?不是、工作、IsAssignableFrom、double

由网友(心里葬着未亡人)分享简介:这是错误的: typeof运算(双).IsAssignableFrom(typeof运算(INT)) 这是错误的: typeof运算(INT).IsAssignableFrom(typeof运算(双)) 不过,这部作品:double a = 1.0;int b = 1;a = b;显然双 是从分配 INT ,但该框...

这是错误的: 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.)

这是值得看的文档Type.IsAssignableFrom (编辑非常轻微的可读性):

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.

阅读全文

相关推荐

最新文章