Trouble with explicit casting
I have a product class in C# that inherits from another product class
using ExternalAssemb.ProductA;
开发者_C百科public class MyProduct : ProductA
{
//....
}
I'm trying to do an explicit cast from ProductA that is in a DLL I reference but it's telling me it's unable to cast
MyProduct myProduct = (MyProduct)productAobject;
Result:: System.InvalidCastException: Unable to cast object of type 'ExternalAssemb.ProductA' to type 'MyAssembly.MyProduct'.
What am I doing wrong?
You can cast a ProductA
reference to a MyProduct
reference, but only if it actually points to MyProductA
or a child thereof.
What you're doing is trying to treat the parent like a child, that's doesn't work. Rather, you can treat the child like the parent, because it is like the parent.
Think of a generic example where a base class is called Shape
and has children such as Square
and Circle
. Given a Shape
reference, you can assign any child to it. But if the reference refers to a Circle
, you can't cast it to a Square
. This makes sense, because all circles are shapes, but no circles are squares.
Hope the examples help.
Quite simply, when you downcast, which may or may not succeed, you need to use is/as
operators to check if the instance of ProductA
is really MyProduct
:
MyProduct myProduct = productAobject as MyProduct;
if (myProduct != null) {
//valid MyProduct instance
} else {
//productAobject is not really an instance of MyProduct
}
Every MyProduct is also a ProductA, but the reverse is not true. productAobject
is an explicit instance of ProductA; it's not a MyProduct at all.
Similarly, given another class:
public class FooProduct : ProductA
{
//....
}
...you could not do this:
ProductA myFooProduct = new FooProduct();
MyProduct myProduct = (MyProduct)myFooProduct;
...since FooProduct does not inherit from MyProduct.
The rule is: you can only cast an instance of a class to itself or one of its ancestor classes. You cannot cast it to any descendant or any other sibling/cousin class in the inheritance tree.
Remember that we're talking about the actual type of the instance here. It is irrelevant what the type of the variable that holds it is.
精彩评论