How do I use a variable declared in a method, outside that method?

后端 未结 6 1454
眼角桃花
眼角桃花 2021-01-27 00:26

I am using VS 2008 (C#)... I have created a function in a GlobalClass to use it globally.. This is for opening a dialog box. When I call this function in my method it works but

6条回答
  •  余生分开走
    2021-01-27 00:53

    You might want to rework your method to actually return the filename instead.

    Something like

    public static string OFDbutton()
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Filter = "Image files|*.jpg;*.jpeg;*.png;*.gif";
    
        if (ofd.ShowDialog() == DialogResult.OK)
            return ofd.Filename;
        else
            return string.Empty;
    }
    

    Of course, this is a very naive approach, and you might want to read up on variable scope and object oriented design in general.

    Edit: This answer expands on the issue and improves the design, taking into account that the user may have clicked cancel in the dialog itself.

    Edit2: Shamelessly copying from the linked answer, I modify my own snippet.

提交回复
热议问题