c# - How do I cast object to inherited class? -


say have:

class tiger: xelement {     public tiger(xelement t)         :base(t) { } } 

and have xdoucment named tigers, how do things like:

xelement t = tigers.descendants("tiger").elementat(0); (tiger)t; t tiger; 

the first 1 throws me exception: cannot cast 't' (which has actual type of 'system.xml.linq.xelement') 'zoo.tiger'
second 1 return null.


trying achieve reference in xelement , cast tiger.
can things xelement.add can directly affect reference in xdocument.

you cannot use inheritance this. object returned elementat xelement, not tiger, , there's nothing can change that. if give furry animal makes meow, there's no way can make dog, though dog subclass of animal.

you can, however, use composition:

class tiger {     public xelement xelement { get; private set; }      public tiger(xelement xelement)     {         this.xelement = xelement;     } } 

usage:

xelement x = tigers.descendants("tiger").elementat(0); tiger t = new tiger(x); t.xelement.add(...); 

(note that, since xelement reference type,

  • t.xelement
  • x and
  • tigers.descendants("tiger").elementat(0)

will refer same xelement object in memory.)


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -