问题
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