How to cast childs of XmlElement to each other?
I have:
public class Element : XmlElement
{
// there is constructor, not important
public string ElementSomething {get;set;}
}
public class Cat: Element {
// there is constructor, not important
public string CatSomething {get;set;}
}
And now an epic question:
public void SomeMethod()
{
XmlElement xmlelem = new XmlElement (/*some params, not important */);
Element elem = new开发者_如何学编程 Element (/*some params, not important*/);
elem.ElementSomething = "Element";
Cat catelem = new Cat(/*some params, not important*/);
catelem .CatSomething = "Cat";
}
How to cast elem
to Cat
and back?
Cat newcat = elem as Cat;
don't work.
You can't - because it's not a Cat
. This has nothing to do with XML at all - it's basic C#. You're trying to do the equivalent of:
object x = new Button();
string s = x as string;
What would you expect the content of s
to be, if this worked?
You can't cast an object reference to a type which the object simply isn't an instance of. You could potentially write a conversion method to create a new object... but a better approach is usually to use composition rather than inheritance in the first place.
You cannot cast a parent into a child class. See also this question: Unable to Cast from Parent Class to Child Class
The other way around is easy:
Cat cat = new Cat(...);
var element = cat as Element;
精彩评论