How do i cast A to object to class A when B can typcast to A?

孤者浪人 提交于 2019-12-08 04:35:55

问题


Basically i want to do this. aa causes a bad cast exception.
NOTE: o can be ANYTHING. It may not be B, it can be C, D, E, F etc. But this should work as long as o is a class that can typecast into A (B is such a class. It uses an implicit operator overload)

        var b = (B)"sz";
        var a = (A)b;
        object o = b;
        var aa = (A)o;

回答1:


Have you tried doing the following?

[...]
var ee = (A)(B)o;

The reason this will work and your code doesn't is that such explicit casts are statically compiled. In other words, when you say (A)o the compiler looks for an explicit cast from object to A and doesn't find one. However, it does determine that A is a subclass of object, so the cast may be viable at runtime - and it inserts an attempt to runtime down-cast the instance into a field of type A. Such runtime casts have nothing to do with explicit and/or implicit conversions; these simply follow the built-in type hierarchy rules.

Another example:

object o = 1.0;
int i = (int)o; //throws InvalidCastException - even though (int)1.0 is OK.


来源:https://stackoverflow.com/questions/2486873/how-do-i-cast-a-to-object-to-class-a-when-b-can-typcast-to-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!