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:

  1. itema.gettype() not return compile-time type of variable itema - returns run-time type of object referred to itema.
  2. there's no way make (a)b result in representation-changing conversion (i.e. new a 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

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -