创建编写器

下面的代码示例创建了一个编写器,编写器是一个可以获取某些类型的数据并将其转换成可传递到流的字节数组的类。

Imports System
Imports System.IO

Public Class MyWriter
    Private s As Stream

    Public Sub New(stream As Stream)
        s = stream
    End Sub

    Public Sub WriteDouble(myData As Double)
        Dim b() As Byte = BitConverter.GetBytes(myData)
        ' GetBytes is a binary representation of a double data type.
        s.Write(b, 0, b.Length)
    End Sub

    Public Sub Close()
        s.Close()
    End Sub
End Class
using System;
using System.IO;

public class MyWriter
{
    private Stream s;

    public MyWriter(Stream stream)
    {
        s = stream;
    }

    public void WriteDouble(double myData)
    {
        byte[] b = BitConverter.GetBytes(myData);
        // GetBytes is a binary representation of a double data type.
        s.Write(b, 0, b.Length);
    }

    public void Close()
    {
        s.Close();
    }
}
using namespace System;
using namespace System::IO;

public ref class MyWriter
{
private:
    Stream^ s;

public:
    MyWriter(Stream^ stream)
    {
        s = stream;
    }

    void WriteDouble(double myData)
    {
        array<Byte>^ b = BitConverter::GetBytes(myData);
        // GetBytes is a binary representation of a double data type.
        s->Write(b, 0, b->Length);
    }

    void Close()
    {
        s->Close();
    }
};

在本示例中,您创建了一个具有构造函数的类,该构造函数带有流参数。 从这里,您可以公开任何需要的 Write 方法。 您必须将编写的所有内容都转换为 byte[]。 在您获得 byte[] 之后,Write 方法将其写入流 s

请参见

概念

基本的文件 I/O

编写流