c# - Permanently cast derived class to base -
class { } class b : { } b itemb = new b(); itema = (a)b; console.writeline(itema.gettype().fullname);
is possible above , have compiler print out type instead of type b. basically, possible permanently cast object "loses" derived data?
what ask impossible 2 reasons:
itema.gettype()
not return compile-time type of variableitema
- returns run-time type of object referred toitema
.- there's no way make
(a)b
result in representation-changing conversion (i.e. newa
object) because user-defined conversion operators (your hope here) cannot convert derived base-classes. you're going normal, safe, reference-conversion.
that aside, ask strange; 1 think you're trying hard violate liskov's substiution principle. there's serious design-flaw here should address.
if still want this; write method manually constructs a
b
newing a
, copying data over. might exist toa()
instance-method on b
.
if characterized problem "how construct an existing a?", makes lot more sense: create copy-constructor on a
, declaration looks public a(a a){...}
, agnostic subclass-specific details. gives general means create a
existing instance of a
or 1 of subclasses.
Comments
Post a Comment