C# 流式传输到 XML 或 html 或其他将来的输出
本文关键字:html 其他 输出 将来 XML 传输 | 更新日期: 2023-09-27 18:37:27
我有一个简单的类XMLSTream,它允许我将数据从应用程序传递到在Word中打开的XML文档。
我有一个简单的类 HTMLStream,它允许我将数据从应用程序传递到在 Internet Explorer 中打开的 HTML 文档。
我的两个流类都可以完美地单独工作。
我已将这些类与匹配的结构对齐,希望用户从文件对话框中选择将确定使用哪个"流类"。我无法弄清楚的是,无论类型如何,如何在调用类中使用相同的代码。
myHtmlStream
{
protected Stream myStream;
protected StreamWriter myWriter;
Open() {// block of code};
Close() {// block of code} ;
WriteLine (string myLine) { // block of code} ;
// etc;
}
myXMLStream
{
protected Stream myStream;
protected StreamWriter myWriter;
Open() {// block of code};
Close() {// block of code} ;
WriteLine (string myLine) { // block of code} ;
// etc;
}
调用类执行以下操作:
SaveFileDialog sDlg = new SaveFileDialog();
sDlg.Filter = "htm files (*.htm)|*.htm|xml files (*.xml)|*.xml";
sDlg.FilterIndex = 1;
if (sDlg.ShowDialog() == DialogResult.OK)
{
if (sDlg.FilterIndex == 1)
{
myHtmlStream mH = new myHtmlStream();
mH.Open();
mH.WriteLine("This is a HTML document");
mH.Close();
}
else if (sDlg.FilterIndex == 2)
{
myXMLStreammX mX= new myXMLStream();
mX.Open();
mX.WriteLine("This is an XML document");
mX.Close();
}
}
您可以看到无论选择哪种文件类型,都会调用相同的步骤,但是向报表添加组件很讨厌,因为它们必须输入两次。(我也有为复杂报告创建表格、填充单元格等的方法。
通过继承,我应该能够简化这一点,任何人都可以链接到任何可能有助于帮助的东西?在实际代码中,它的方式是超过4行XML/HTML输出的实际数据。我知道理论上至少有一种优雅的方法来解决这个问题
在我看来,这里最好的解决方案是定义一个接口和一个抽象类。
定义如下内容:
public interface IOutputStream
{
void Open();
void Close();
void WriteLine(string line);
}
public abstract class OutputStreamBase : IOutputStream
{
// create cross-cutting concerns here, logging, file handling, etc.
// create virtual methods and properties that are common to all descendants
public virtual void Open()
{
throw new System.NotImplementedException();
}
public virtual void Close()
{
throw new System.NotImplementedException();
}
public virtual void WriteLine(string line)
{
throw new System.NotImplementedException();
}
protected virtual void DoSomething()
{
}
protected abstract void DoSomethingElse();
}
然后,一旦有了这些,您就可以根据需要定义任意数量的具体实现:
public class HtmlStream : OutputStreamBase
{
protected override void DoSomethingElse()
{
throw new System.NotImplementedException();
}
}
public class XmlStream : OutputStreamBase
{
protected override void DoSomethingElse()
{
throw new System.NotImplementedException();
}
}
然后,在调用代码中,创建一个 IOutputStream 类型的变量,并根据需要分配它:
public void Test()
{
IOutputStream outputStream;
if (sDlg.ShowDialog() == DialogResult.OK)
{
if (sDlg.FilterIndex == 1)
outputStream = new HtmlStream();
else if (sDlg.FilterIndex == 2)
outputStream = new XmlStream();
else
throw new InvalidOperationException();
}
outputStream.Open();
outputStream.WriteLine("ContentHere");
outputStream.Close();
}
}
然后,无论实现如何,都可以使用相同的方法调用。
由于您正在处理文件、流等资源,因此实现 IDisposable 接口也是谨慎的,并将整个事情包装在一个(使用 var stream = ... )块中,以确保您的资源在完成后被刷新、关闭和处置。