C# Using StreamReader

來源:互聯網
上載者:User
=== Program that uses StreamReader [C#] ===

using System;
using System.IO;

class Program
{
    static void Main()
    {
        //
        // It will free resources on its own.
        //
        string line;
        using (StreamReader reader = new StreamReader("file.txt"))
        {
            line = reader.ReadLine();
        }
        Console.WriteLine(line);
    }
}

=== Program that uses Dispose [C#] ===

using System;
using System.IO;

class Program
{
    static void Main()
    {
        //
        // Read a line from a file the old way.
        //
        StreamReader reader = new StreamReader("file.txt");
        string line = reader.ReadLine();
        reader.Close();
        // You should call Dispose on 'reader' here, too.
        reader.Dispose();
        Console.WriteLine(line);
    }

}

 

  Why use using?  參照http://ryanfarley.com/blog/archive/2004/03/18/447.aspx 中作者解釋

 

Even without understanding MSIL, you can clearly see what is going on here. The code was essentially translated to a try/finally block calling Dispose in the finally. If I were to take this same IL and convert it back to C# using Reflector then it would be exactly that, a try/finally block where Dispose is called in the finally.

So why use using at all? If all using does is translate to a try/finally block then why would you want to use it? Well, as I said at the beginning, it really does come down to a matter of preference. I think the code is more elegant but others may not and that is OK. However, take any peice of code that does not use using and tell me that Dispose is being called without looking in the finally block. You can't. There's no way you can guarantee that Dispose is being called without looking in the finally block to see. With using, there's nothing to look at. You know it is being called. You know that there's no way you could have forgotten to call Dispose and left some references to unmanaged resources out there somewhere. You know this because it is done automatically for you - and I think that is just cool.

To finish things up, it is important to understand that since the purpose of using is to create a scope for an object where Dispose is automatically called upon leaving the scope that this requires that the object actually implements IDisposable. Using an object that does not implement IDisposable will result in an error, just as manually calling Dispose for the object in a finally block would result in an error. For a list of objects in the framework that implement IDisposable you can look at the IDisposable definition in the docs. However, with that said, you should also implement IDisposable in your own classes that use unmanaged resources such as interop etc.

 

google翻譯

 

即使不理解的MSIL,你可以清楚地看到這裡發生了什麼。該代碼基本上轉化為一個try / finally塊中調用最終處置。如果我要採取同樣的IL和它轉換到C#中使用反射鏡,然後便正是這樣一個try / finally塊丟棄在這裡終於被調用。

那麼,為什麼用使用呢?如果全部採用所做的是翻譯成一個try / finally塊那你為什麼要使用它?嗯,正如我在開始時說,它確實可以歸結為一個見仁見智的問題。我認為代碼更優雅,但其他人可能不會,這是確定。但是,採取任何的代碼使用和不使用沒有告訴在finally塊找我,被調用Dispose的一塊。你不能。有沒有辦法可以保證不被丟棄在finally塊來看看尋找調用。與使用,有什麼可看。你知道這是被調用。你知道,有沒有你可能忘記調用Dispose,離開那裡有些地方的非託管資源的引用方式。你知道這是因為它是為您自動完成 - 我認為這隻是冷靜。

要完成的事情了,重要的是要明白,自從使用目的是建立一個為在離開時自動Dispose的範圍,這需要該對象實際實現IDisposable稱為對象的範圍。使用對象不實現IDisposable將導致一個錯誤,就像手動finally塊中調用該對象的Dispose將導致錯誤。如需在架構中實現IDisposable對象的列表,你可以看看在docs IDisposable介面的定義。然而,隨著中說,你也應該在自己的類實現IDisposable介面,使用非託管資源互操作等,

 

Server.MapPath() 探究 (轉)
Server.MapPath(path)
       The MapPath method maps the specified relative or virtual path to the corresponding physical directory on the server.
Parameters (MSDN:ms-help://MS.MSDNQTR.2003FEB.2052/iisref/htm/ref_vbom_serommp.htm)
用法:
1.Server.MapPath("/")  應用程式根目錄所在的位置 如 C:\Inetpub\wwwroot\
2.Server.MapPath("./")  表示所在頁面的目前的目錄
    註:等價於Server.MapPath("")  返回 Server.MapPath("")所在頁面的物理檔案路徑
3.Server.MapPath("../")表示上一級目錄
4.Server.MapPath("~/")表示當前應用級程式的目錄,如果是根目錄,就是根目錄,如果是虛擬目錄,就是虛擬目錄所在的位置 如:C:\Inetpub\wwwroot\Example\
註:等效於Server.MapPath("~")。

不知道是否正確,研究中......
另:以下幾句等效
string filename=Server.MapPath("./") + @"\Web.config";
string filename=Server.MapPath("./") + "/Web.config";
string filename=Server.MapPath("") + @"\Web.config"

附一例子:修改web.config的某一節點的屬性值
    public void write()
        {
            string key1 = this.TextBox1.Text;
            DataSet ds = new DataSet();
            ds.ReadXml(Server.MapPath("")+"/web.config");
            // 不是Tables[0]
            ds.Tables[1].Rows[0][1] = key1;
            ds.AcceptChanges();
            ds.WriteXml(Server.MapPath("")+"/web.config");
            ds.Dispose();           
        }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.