简体   繁体   English

从System.XmlWriter投射到System.XmlTextWriter

[英]Casting from System.XmlWriter to System.XmlTextWriter

How can I cast XmlWriter to XmlTextWriter in C#? 如何在C#中将XmlWriter转换为XmlTextWriter?

thanks 谢谢

XmlTextWriter subclasses XmlWriter, so, if your XmlWriter is indeed an XmlTextWriter, you can just cast it like anything else. XmlTextWriter继承了XmlWriter的子类,因此,如果您的XmlWriter确实是XmlTextWriter,则可以将其像其他任何类型一样进行转换。 If your XmlWriter is any other subclass of XmlWriter, your cast would fail. 如果您的XmlWriter是XmlWriter的任何其他子类,则强制转换将失败。

You can check the type and then cast 您可以检查类型,然后进行投射

if (xmlWriter is XmlTextWriter)
{
    XmlTextWriter xmlTextWriter = (XmlTextWriter)xmlWriter;
    // add code here
}

Or you can use as to give it a shot and then see if it worked out. 或者,您可以使用as尝试一下,然后查看是否可行。

XmlTextWriter xmlTextWriter = xmlWriter as XmlTextWriter;

if (null != xmlTextWriter)
{
    // add code here
}

XmlTextWriter is inheriting from XmlWriter . XmlTextWriterXmlWriter继承。 So unless the XmlWriter you have is an XmlTextWriter , you can't cast it that way. 因此,除非您拥有的XmlWriterXmlTextWriter ,否则您将无法以这种方式进行转换。 You could do 你可以做

var textWriter = xmlWriter as XmlTextWriter;
if (textWriter != null)
{
    ...
}

Why not instantiate the XmlTextWriter to begin with? 为什么不实例化XmlTextWriter呢?

The same way you would perform any other cast (assuming your instance is actually an XmlTextWriter). 与执行其他任何强制类型转换的方式相同(假设您的实例实际上是XmlTextWriter)。

The following case below works: 以下情况适用:

using System;
using System.Xml;

class Test
{
     static void Main(string[] args)
     {
          XmlWriter xmlWriter = XmlWriter.Create("MyXml.xml");
          XmlTextWriter xmlTextWriter = xmlWriter as XmlTextWriter;
          if(xmlTextWriter != null)
          {
               //perform operations here...
          }
     }   
}

You should note they recommend using XmlWriter.Create to create XmlWriter instances. 您应该注意,他们建议使用XmlWriter.Create创建XmlWriter实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM