【问题标题】:XmlTextWriter Inheritance and Cast ExceptionXmlTextWriter 继承和强制转换异常
【发布时间】:2015-09-09 18:11:18
【问题描述】:

我想创建一个 XmlTextWriter 的扩展,其中包含许多自定义方法来写下我在自己的文件格式中使用的类和结构(我不想使用序列化,因为有时标签嵌套可能非常深因此定义所有 XmlElement 属性并创建所有必要的投影会非常繁琐)。 这是我所做的:

public sealed class MySpecialWriter : XmlTextWriter
{
    private static readonly XmlWriterSettings s_DefaultSettings = new XmlWriterSettings
    {
        CloseOutput = true,
        Encoding = new UTF8Encoding(false),
        Indent = true,
        IndentChars = "\t",
        NewLineChars = Environment.NewLine,
        NewLineHandling = NewLineHandling.Replace,
        OmitXmlDeclaration = false,
    };

    public MySpecialWriter(Stream output, Encoding encoding) : base(output, encoding) { }

    public MySpecialWriter(String output, Encoding encoding) : base(output, encoding) { }

    public MySpecialWriter(TextWriter output) : base(output) { }

    public static MySpecialWriter Initialize(StringBuilder sb)
    {
        return (MySpecialWriter)Create(sb, s_DefaultSettings);
    }

    public void WriteMyClass(MyClass value)
    {
        ...
    }
}

当我尝试使用它时(只是一个简单的测试,看看它是否有效):

StringBuilder sb = new StringBuilder();

try
{
    using (MySpecialWriter writer = MySpecialWriter.Initialize(sb))
    {
        writer.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
        writer.WriteMyClass(value)
        writer.Flush();
    }
}
catch (Exception e)
{
    return null;
}

return sb.ToString();

我从“初始化”方法中得到以下异常:

无法将“System.Xml.XmlWellFormedWriter”类型的对象转换为“System.Xml.XmlTextWriter”类型。

你能帮帮我吗?

【问题讨论】:

    标签: c# .net xml inheritance casting


    【解决方案1】:

    当你这样做时:

    return (MySpecialWriter)Create(sb, s_DefaultSettings);
    

    Create 指的是XmlWriter.Create 方法,它返回XmlTextWriter 的实例,而不是MySpecialWriter 的实例,所以转换失败。您应该只使用new 来创建您的类的实例。

    无论如何,我不认为你真的需要在这里继承XmlTextWriter(除非你特别需要使用XmlTextWriter 的受保护方法,这不太可能)。通过为XmlWriter 编写扩展方法,您可能会获得相同的结果。

    【讨论】:

      猜你喜欢
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      • 2010-11-30
      • 2017-06-16
      • 2021-10-24
      相关资源
      最近更新 更多