【问题标题】:How to cast childs of XmlElement to each other?如何将 XmlElement 的孩子相互转换?
【发布时间】:2011-04-28 16:33:00
【问题描述】:

我有:

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;

不工作。

【问题讨论】:

    标签: c# .net xml


    【解决方案1】:

    你不能 - 因为它不是Cat。这与 XML 完全无关——它是基本的 C#。您正在尝试执行以下操作:

    object x = new Button();
    string s = x as string;
    

    如果可行,您希望s 的内容是什么?

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

    【讨论】:

      【解决方案2】:

      您不能将父类转换为子类。另请参阅此问题:Unable to Cast from Parent Class to Child Class

      反过来很简单:

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

      【讨论】:

        猜你喜欢
        • 2018-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-09
        • 1970-01-01
        • 2015-07-15
        • 1970-01-01
        相关资源
        最近更新 更多