Casting between inherited classed
The following cast doent work. I think it should, can you explain to me why not? Both WebserviceErrorMessage
and BTMacResponse
inherit from the WebserviceMessage
class
开发者_如何学Go DataLayer.WebserviceMessage msg = new Service.WebserviceErrorMessage(ex) ;
DataLayer.BTMacResponse macrsp = (DataLayer.BTMacResponse)msg;
Unless WebserviceErrorMessage
inherits from BTMacResponse
, I don't see why this should work. You're trying to cast a value to BTMacResponse
when the object simply isn't a BTMacResponse
.
To put it another way, would you expect to be able to cast a FileStream
to a MemoryStream
just because they both inherit from Stream
?
Would you expect to be able to cast a Button
to a String
just because they both inherit from Object
?
You can't cast that way. The following is illegal:
class Base {
}
class A : Base {
}
class B: Base {
}
Base someBase = new A();
B someB = (B)someBase;
You cannot cast down the hierarchy because when you create an object of the parent, you do not create the child object with it, however when you create an object of the child an instance of the parent is created, thats why you can upcast and not downcast.
in your case you can cast DataLayer.WebserviceMessage to its children and not the opposite.
there is no contractor for DataLayer.BTMacResponse that get DataLayer.WebserviceMessage as a parameter you need to implement this:
public BTMacResponse(WebserviceMessage w)
{
// copy stuff to 'this'
}
public static implicit operator BTMacResponse(WebserviceMessage w)
{
BTMacResponse b = new BTMacResponse(w);
return b;
}
精彩评论