当我在if / else子句中实例化Textwriter对象时,它在子句外部不可见。我能在这做什么?我想要附加或写一个新文件。
以下是代码:
private static void eventfull_doing()
{
string path, line;
int countLines;
Console.Write("Enter the name(with extension) of the file in the \"data\" folder, or create a new name(with extension): ");
path = Console.ReadLine();
TextReader inFile = new StreamReader(@"C:\data\" + path);
Console.Write("How many lines of text do you want to add to the file?: ");
countLines = Convert.ToInt32(Console.ReadLine());
if (inFile.Peek() == -1 || inFile == null)
{
TextWriter outFile = File.AppendText(@"C:\data\" + path);
}
else
{
TextWriter outFile = new StreamWriter(@"C:\data\" + path);
}
for (int i = 0; i < countLines; i++)
{
Console.Write("Enter line: ");
line = Console.ReadLine();
outFile.
}
以下是我所做的:请注意,在第一个片段中,if条件不符合预期。
string path, line;
int countLines;
Console.Write("Enter the name(with extension) of the file in the \"data\" folder, or create a new name(with extension): ");
path = Console.ReadLine();
string file = Path.Combine(@"c:\data", path);
Console.Write("How many lines of text do you want to add to the file?: ");
countLines = Convert.ToInt32(Console.ReadLine());
TextWriter outFile = null;
if (File.Exists(file))
{
using (outFile = File.AppendText(file))
{
for (int i = 0; i < countLines; i++)
{
Console.Write("Enter line: ");
line = Console.ReadLine();
outFile.WriteLine(line);
}
}
}
else
{
using (outFile = new StreamWriter(file))
{
for (int i = 0; i < countLines; i++)
{
Console.Write("Enter line: ");
line = Console.ReadLine();
outFile.WriteLine(line);
}
}
}
}
答案 0 :(得分:5)
您可以在if
语句之前声明它,但没有赋值 - 然后确保在两个分支中为它分配值:
TextWriter outFile;
if (inFile.Peek() == -1 || inFile == null)
{
outFile = File.AppendText(@"C:\data\" + path);
}
else
{
outFile = new StreamWriter(@"C:\data\" + path);
}
但是,如果文件存在,您仍然可以打开该文件,这可能会导致您出现问题 - 如果您发现它仍为空,则不清楚为什么要调用File.AppendText
。你实际只是想创建或追加?如果是这样,只需使用AppendText
- 就可以了。
您还应该使用using
语句自动关闭编写器...如果您 需要在多个地方使用@"C:\data\" + path
,我会提取对局部变量的通用表达式:
string file = Path.Combine(@"c:\data", path);
// Now use file everywhere
如果您 坚持使用File.AppendText
或StreamWriter
构造函数,请考虑使用条件表达式:
TextWriter outFile = inFile.Peek() == -1 || inFile == null
? File.AppendText(file) : new StreamWriter(file);
答案 1 :(得分:3)
这是设计的。你需要写一些类似的东西:
TextWriter outFile = null;
if (inFile.Peek() == -1 || inFile == null)
{
outFile = File.AppendText(@"C:\data\" + path);
}
else
{
outFile = new StreamWriter(@"C:\data\" + path);
}
在这种情况下,null
到outfile的赋值是可选的,但是当你在某个时候用C ++开始编码时,你会发现这是一个很好的做法。
答案 2 :(得分:1)
请在外面宣布并在里面实例化,
这是正常的行为,如果你在一个代码块中声明一个只能使用该代码块的变量,那么请在CodeBlock之外声明变量并在if else
代码块中实例化或分配一些东西
错误
if ( condition )
{
string s = "J" ;
}
MessageBox.Show(s)
<强>正确强>
string s ;
if ( condition )
{
s = "jo";
}
MessageBox.Show(s) ;