Announcement

Collapse
No announcement yet.

Was bewirkt das using im Code???

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Was bewirkt das using im Code???

    Ich habe in einem Codesnippet folgenden Konstrukt gesehen.
    <pre>
    using (FileStream fs = File.Create(path))
    {
    AddText(fs, "This is some text");
    AddText(fs, "This is some more text,");
    AddText(fs, "\r\nand this is on a new line");
    AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");

    for (int i=1;i < 120;i++)
    {
    AddText(fs, Convert.ToChar(i).ToString());

    //Split the output at every 10th character.
    if (Math.IEEERemainder(Convert.ToDouble(i), 10) == 0)
    {
    AddText(fs, "\r\n");
    }
    }
    }

    //Open the stream and read it back.
    using (FileStream fs = File.OpenRead(path))
    {
    byte[] b = new byte[1024];
    UTF8Encoding temp = new UTF8Encoding(true);
    while (fs.Read(b,0,b.Length) > 0)
    {
    Console.WriteLine(temp.GetString(b));
    }
    }
    </pre>
    Was bedeutet das using(.....)??

  • #2
    Hallo,

    das <b>using</b> ist eine Kurzform für folgenden Code:
    <pre>
    FileStream fs = File.Create(path);
    try {
    AddText...
    }
    finally {
    <b>fs.Dispose();</b>
    }
    </pre>
    Er ruft also autom. die Dispose()-Methode auf. Funktioniert aber nur, wenn die Klasse das IDisposable-Interface implemtiert. Sonst gibt es eine Compiler-Fehlermeldung.

    Schöen Grüße

    Jör

    Comment

    Working...
    X