C# 如何将XmlElement的子元素相互转换?

C# 如何将XmlElement的子元素相互转换?,c#,.net,xml,C#,.net,Xml,我有: 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;} } public

我有:

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;}

}
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";  
}
现在是一个史诗般的问题:

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;}

}
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";  
}
如何将
elem
转换为
Cat
并返回?

Cat newcat = elem as Cat;
不要工作。

你不能-因为它不是猫。这与XML毫无关系——它是基本的C语言。您正在尝试执行以下等效操作:

object x = new Button();
string s = x as string;
如果这样做有效,您希望
s
的内容是什么

不能将对象引用强制转换为该对象不是其实例的类型。您可能会编写一个转换方法来创建新对象。。。但是一个更好的方法通常是首先使用组合而不是继承。

你不能——因为它不是一个
Cat
。这与XML毫无关系——它是基本的C语言。您正在尝试执行以下等效操作:

object x = new Button();
string s = x as string;
如果这样做有效,您希望
s
的内容是什么


不能将对象引用强制转换为该对象不是其实例的类型。您可能会编写一个转换方法来创建新对象。。。但更好的方法通常是首先使用组合而不是继承。

不能将父类强制转换为子类。另见这个问题:

另一种方法很简单:

 Cat cat = new Cat(...);
 var element = cat as Element;

不能将父类强制转换为子类。另见这个问题:

另一种方法很简单:

 Cat cat = new Cat(...);
 var element = cat as Element;