문제

How would I go about writing my own stream manipulator class?

Basically what I'm trying to wrap my head around is storing the reference to the underlying stream in the writer. For example, when writing to a memory stream using a StreamWriter, when a Write() is made, the underlying memory stream is written to.

Can I store the reference to an underlying stream without using pointers or unsafe code? Even if it was just a string I wanted to "write" to.

Really this has little to do with stream writers, and I'm just wondering how I could store references in a class. The StreamWriter was the best example I could come up with for this.

도움이 되었습니까?

해결책

No unsafe code is needed. Check out this example I put together.

public sealed class StreamManipulator
{
    private readonly Stream _backingStream;

    public StreamManipulator(Stream backingStream)
    {
        _backingStream = backingStream;
    }

    public void Write(string text)
    {
        var buffer = Encoding.UTF8.GetBytes(text);
        _backingStream.Write(buffer, 0, buffer.Length);        
    }
}

다른 팁

Just declare a property of type Stream and assign some value to it. If you post some code you could get a bit clearer answer. Here's a sample though.

class foo
{
    public MemoryStream MyMemory { get; set; }

    public void Write(string s)
    {
        MyMemory.Write(System.Text.Encoding.ASCII.GetBytes(s));
    }

    [STAThread]
    static void Main()
    {
        foo f = new foo();
        f.MyMemory = new System.IO.MemoryStream();

        f.Write("information");
    }

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top