[英]The name 'sr' doesn't exist in current context
我正在關注微軟網站上的示例,以便從文本文件中讀取。 他們說是這樣做的:
class Test
{
public static void Main()
{
try
{
using (StreamReader sr = new StreamReader("TestFile.txt"));
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
但是當我在Visual C#2010中這樣做時,它會給我帶來錯誤:
可能是錯誤的空話
在當前上下文中不存在名稱'sr'
我刪除了using
部分,現在代碼看起來像這樣,並且正在工作:
try
{
StreamReader sr = new StreamReader("TestFile.txt");
string line = sr.ReadToEnd();
Console.WriteLine(line);
}
這是為什么?
更新: using(....);
結束時有分號using(....);
你所描述的是通過推桿實現的;
使用聲明后
using (StreamReader sr = new StreamReader("TestFile.txt"));
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
可能你甚至沒有注意到並在以后刪除。
使用(StreamReader)和StreamReader有什么區別?
當您將一次性變量(StreamReader)放入using語句時,它與以下內容相同:
StreamReader sr = new StreamReader("TestFile.txt");
try
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
finally
{
// this block will be called even if exception occurs
if (sr != null)
sr.Dispose(); // same as sr.Close();
}
此外,如果您在使用塊中聲明變量,它將僅在使用塊中可見。 那就是為什么;
使您的StreamReader在后一種情況下不存在。 如果在使用塊之前聲明sr
,它將在稍后顯示,但將關閉流。
我只是添加了這個答案,因為現有的答案(雖然正確投票)只是告訴你錯誤是什么,而不是為什么它是一個錯誤。
這樣做;
using (StreamReader sr = new StreamReader("TestFile.txt"));
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
實際上與執行此操作相同(語義上):
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
// Note that we're not doing anything in here
}
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
第二個塊(由第二組花括號創建)與using
塊沒有任何關系。 由於在using
塊中定義的變量僅在該塊的范圍內,因此一旦您的代碼到達第二個塊,它就不存在(就在范圍和可訪問性方面)。
您應該使用using
語句,因為StreamReader
實現了IDisposable
。 using
塊提供了一種簡單,干凈的方式,以確保 - 即使在例外情況下 - 您的資源也得到了適當的清理。 有關using
塊的更多信息(具體而言, IDisposable
接口是什么),請參閱IDisposable
標記上的元描述 。
改變這個:
using (StreamReader sr = new StreamReader("TestFile.txt"));
對此:
using (StreamReader sr = new StreamReader("TestFile.txt"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.