处理在另一个对象的构造函数中使用的对象

时间:2012-02-06 07:59:42

标签: c# .net oop dispose using

我正在使用此代码从隔离存储中读取值

        IsolatedStorageFile isoStore = null;
        StreamReader reader = null;
        IsolatedStorageFileStream isolatedStorageFileStream = null;
        String strIsolatedStorageValue = string.Empty;

        isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);

        try
        {
            isolatedStorageFileStream = new IsolatedStorageFileStream(strKey + ".txt", FileMode.OpenOrCreate, isoStore);
            // This code opens the store and reads the string.
            reader = new StreamReader(isolatedStorageFileStream);

            // Read a line from the file and add it to sb.
            strIsolatedStorageValue = reader.ReadLine();
        }
        catch (Exception)
        {

        }
        finally
        {
            if (isolatedStorageFileStream != null)
            {
                isolatedStorageFileStream.Dispose();
            }
            if (reader != null)
            {
                reader.Dispose();
            }
        }

        // Return the string.
        return strIsolatedStorageValue;

问题在于,当我处理isolatedStorageFileStream然后处理读取器时,visual studio告诉我,IsolatedStorageFileStream可以被多次处理!当没有处理它时,我收到的警告是应该首先处理isolatedStorageFileStream。

在这种情况下该做什么,即处理在另一个一次性对象的构造函数中使用的对象

由于

3 个答案:

答案 0 :(得分:1)

使用using关键字:

using (IsolatedStorageFileStream isolatedStorageFileStream = 
       new IsolatedStorageFileStream(
            strKey + ".txt", FileMode.OpenOrCreate, isoStore))
using (StreamReader reader = new StreamReader(isolatedStorageFileStream))
{
    // Read a line from the file and add it to sb.
    strIsolatedStorageValue = reader.ReadLine();
}

return strIsolatedStorageValue;

using为您安全地拨打Dispose,您无需手动拨打电话。

答案 1 :(得分:1)

您应该在文件流之前处理阅读器。

要简化代码,您应该使用using块。他们为您自动执行try / finally / dispose模式:

using (isolatedStorageFileStream = new IsolatedStorageFileStream(
          strKey + ".txt", FileMode.OpenOrCreate, isoStore)) {
    // This code opens the store and reads the string.
    using (reader = new StreamReader(isolatedStorageFileStream)) {
        strIsolatedStorageValue = reader.ReadLine();
   }
}

答案 2 :(得分:1)

对于你来说,using statement会自动为IDisposable(如果不为null,则为dispos)进行try-finally。

using (IsolatedStorageFileStream isolatedStorageFileStream = new IsolatedStorageFileStream(strKey + ".txt", FileMode.OpenOrCreate, isoStore))
{
    using (StreamReader reader = new StreamReader(isolatedStorageFileStream))
    {
        string strIsolatedStorageValue = reader.ReadLine();
        return strIsolatedStorageValue;
    }
}