C# error: Operator '==' cannot be applied

2019-08-13 23:25发布

On Visual Studio C# Express when I run the script below, I get the following error message on the line saying:

if (ofd.ShowDialog() == true): Error 1 Operator '==' cannot be applied to operands of type 'System.Windows.Forms.DialogResult' and 'bool'

How could I solve this? Code below:

public override GH_ObjectResponse RespondToMouseDoubleClick(GH_Canvas sender, GH_CanvasMouseEvent e)
{
    System.Windows.Forms.OpenFileDialog ofd = new  System.Windows.Forms.OpenFileDialog();
    ofd.Multiselect = true;

    ofd.Filter = "Data Sources (*.ini)|*.ini*|All Files|*.*";
    if (ofd.ShowDialog() == true)
    {
        string[] filePath = ofd.FileNames;
        string[] safeFilePath = ofd.SafeFileNames;
    }
    return base.RespondToMouseDoubleClick(sender, e);
}

3条回答
forever°为你锁心
2楼-- · 2019-08-13 23:48

Replace it with:

if (ofd.ShowDialog() == DialogResult.OK)

ShowDialog method returns DialogResult enumeration, which has following members:

  • None
  • OK
  • Cancel
  • Abort
  • Retry
  • Ignore
  • Yes
  • No
查看更多
Fickle 薄情
3楼-- · 2019-08-14 00:00

Compare with on of the values defined for DialogResult like DialogResult.OK not boolean.

if (ofd.ShowDialog() == DialogResult.OK)
{

}

Possible values of DialogResults are given below. compare with the one you require.

DialogResult.None
DialogResult.OK
DialogResult.Cancel
DialogResult.Abort
DialogResult.Retry
DialogResult.Ignore
DialogResult.Yes
DialogResult.No
查看更多
Fickle 薄情
4楼-- · 2019-08-14 00:02

I suspect you've been reading the WPF OpenFileDialog.ShowDialog documentation where the method result is Nullable<bool>. If, however, you're using Windows Forms OpenFileDialog.ShowDialog, that returns DialogResult - which you clearly can't compare with bool.

Have a look at DialogResult and see what you actually want to do. Note that the documentation claims:

Return: DialogResult.OK if the user clicks OK in the dialog box; otherwise, DialogResult.Cancel.

... so those should be the only cases you need to consider.

查看更多
登录 后发表回答