单声道?实际使用变量时CS0219警告

tig*_*tig 0 c# mono monodevelop

MonoDevelop(2.10.8)正在报道:

JPGCorruptForm.cs(20,20): Warning CS0219: The variable `myStream' is assigned but its value is never used (CS0219) (JPGCorrupt)
Run Code Online (Sandbox Code Playgroud)

对于这个功能:

    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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我的单一测试项目,我不确定这种事情是否正常.它当然不是致命的,但可能会令人讨厌.

Jon*_*eet 8

那么你分配一个值的变量,但你从来没有真正阅读从它.换句话说,您可以轻松删除它,只需将中间表达式更改为:

if (openFileDialog.OpenFile() != null)
Run Code Online (Sandbox Code Playgroud)

请注意,即使您可能认为在比较为null时,您的现有代码实际上并未从变量中读取.它更像是这样的:

Stream tmp = openFileDialog.OpenFile();
myStream = tmp;
if (tmp != null)
Run Code Online (Sandbox Code Playgroud)

听起来你可能应该使用它,如果没有别的话就关闭流......虽然我会尽可能晚地声明它,如下所示:

using (Stream myStream = openFileDialog.OpenFile())
{
    if (myStream != null)
    {
        _settings.TextFile = openFileDialog.FileName;
        CurrentTextFile = _settings.TextFile;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个相同问题的简单例子,但方式如下:

using System;

class Test
{
    static void Main()
    {
        string x;

        if ((x = "Hello") != null)
        {
            Console.WriteLine("Yes");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,警告级别为4(可能还有较低级别),Microsoft C#4编译器也会选中它:

Test.cs(7,16): warning CS0219: The variable 'x' is assigned but its value is
        never used
Run Code Online (Sandbox Code Playgroud)