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

时间:2012-02-13 06:25:47

标签: 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)

对于此功能:

    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);
            }
        }
    }

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

1 个答案:

答案 0 :(得分:8)

你是为变量分配一个值,但你实际上从来没有从中读取。换句话说,您可以轻松删除它,只需将中间表达式更改为:

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;
    }
}

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

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
相关问题