[英]The name “…” does not exist in the current context. error
I am using a book to learn C# in which I was asked to type the following code but for InFile
and OutFile
used in the code it says: 我正在使用一本书来学习C#,要求我在其中键入以下代码,但对于代码中使用的
InFile
和OutFile
却说:
The name "InFile" does not exist in the current context.
名称“ InFile”在当前上下文中不存在。 and The name "OutFile" does not exist in the current context.
在当前上下文中不存在名称“ OutFile”。
Code is given below: 代码如下:
using System;
using System.IO;
class NumberIt
{
public static void Main(string[] args)
{
if (args.Length <= 0)
{
Console.WriteLine("\nYou need to include a filename.");
}
else
{
StreamReader InFile = null;
StreamWriter OutFile = null;
}
try
{
InFile = File.OpenText(args[0]);
OutFile = File.CreateText("OutFile.txt");
Console.Write("\nNumbering...");
string line = InFile.ReadLine();
int ctr = 1;
while (line != null)
{
OutFile.WriteLine("{0}:{1}", ctr.ToString().PadLeft(3, '0'), line);
Console.Write("..{0}..", ctr.ToString());
ctr++;
line = InFile.ReadLine();
}
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("Could not find the file {0}", args[0]);
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
finally
{
if (InFile != null)
{
InFile.Close();
OutFile.Close();
Console.WriteLine("...Done");
}
}
}
}
The variables are declared, but within a different scope. 声明了变量,但是在不同的范围内。 A 'scope' is -generally speaking- code within curly braces.
“范围”通常是花括号中的代码。
A declaration of variables is not a statement, so you cannot read your code like 'if the arguments are ok, then declare the two variables'. 变量的声明不是语句,因此您不能像“如果参数正确,则声明两个变量”那样阅读代码。 A variable declaration should be read like 'Here are two containers of type XY which will be known until the scope ends..'.
变量声明应类似于“这里是两个XY类型的容器,直到作用域结束才知道。”。
So your code should look similar to this. 因此,您的代码应与此类似。
public static void Main(string[] args)
{
if (args.Length <= 0)
{
Console.WriteLine("\nYou need to include a filename.");
}
else
{
StreamReader InFile = null;
StreamWriter OutFile = null;
try
{
InFile = File.OpenText(args[0]);
OutFile = File.CreateText("OutFile.txt");
Console.Write("\nNumbering...");
...
}
catch ...
{
}
// InFile and OutFile still known here !
}
// InFile and OutFile are unknown here !
Hope this describes what others already mentioned. 希望本文能够描述其他人已经提到的内容。
you should declare InFile and Outfile in the scope of your Main method, or outside of the Main. 您应该在Main方法的范围内或Main之外声明InFile和Outfile。
class NumberIt
{
// declare them here
public static void Main(string[] args)
{
// or here
...
}
}
The variables InFile and OutFile are out of scope for the try/catch block. 变量InFile和OutFile在try / catch块的范围之外。
Move the try/catch
block inside the else statement above it, so the variables are still available. 将
try/catch
块移到其上方的else语句内,因此变量仍然可用。 Easiest is to move the }
above try
to the very end. 最简单的是移动
}
上面try
到了最后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.