C# 单盲蝽?CS0219实际使用变量时的警告
Monodevel(2.10.8)报告:C# 单盲蝽?CS0219实际使用变量时的警告,c#,mono,monodevelop,C#,Mono,Monodevelop,Monodevel(2.10.8)报告: JPGCorruptForm.cs(20,20): Warning CS0219: The variable `myStream' is assigned but its value is never used (CS0219) (JPGCorrupt) 对于此功能: private void toolStripButtonChooseText_Click(object sender, EventArgs e) { St
JPGCorruptForm.cs(20,20): Warning CS0219: The variable `myStream' is assigned but its value is never used (CS0219) (JPGCorrupt)
对于此功能:
private void toolStripButtonChooseText_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = ".";
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = false;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
Stop();
try
{
if ((myStream = openFileDialog.OpenFile()) != null)
{
_settings.TextFile = openFileDialog.FileName;
CurrentTextFile = _settings.TextFile;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
这是我的第一个单声道测试项目,我不确定这种情况是否正常。这当然不是致命的,但可能会让人恼火。你给变量赋值,但你从来没有真正从中读取数据。换句话说,只需将中间表达式更改为:
if (openFileDialog.OpenFile() != null)
请注意,您现有的代码实际上并没有从变量中读取数据,即使您可能认为它在与null的比较中读取数据。更像这样:
Stream tmp = openFileDialog.OpenFile();
myStream = tmp;
if (tmp != null)
using (Stream myStream = openFileDialog.OpenFile())
{
if (myStream != null)
{
_settings.TextFile = openFileDialog.FileName;
CurrentTextFile = _settings.TextFile;
}
}
听起来你可能应该用它来关闭流,如果没有其他的。。。尽管我会尽可能晚地宣布,比如:
Stream tmp = openFileDialog.OpenFile();
myStream = tmp;
if (tmp != null)
using (Stream myStream = openFileDialog.OpenFile())
{
if (myStream != null)
{
_settings.TextFile = openFileDialog.FileName;
CurrentTextFile = _settings.TextFile;
}
}
下面是同一问题的一个简单示例,但方法如下:
using System;
class Test
{
static void Main()
{
string x;
if ((x = "Hello") != null)
{
Console.WriteLine("Yes");
}
}
}
请注意,对于警告级别4(可能更低),Microsoft C#4编译器也会注意到这一点:
Test.cs(7,16): warning CS0219: The variable 'x' is assigned but its value is
never used
我认为警告信息足够清楚,可以理解吗?谢谢,乔恩。CurrentTextFile的set()打开该文件,因此我确实希望在调用该文件之前将其关闭。现在我理解了我的错误,我将对此进行一点修改。Microsoft C#4编译器采用了您的示例,但无法捕捉原始情况,因为它仅在赋值操作的RHS为编译时常量时才会引发CS0219。(见附件)。