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

后端 未结 6 1443
眼角桃花
眼角桃花 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 01:01

    When you declare a variable inside a method, then the variable is scoped to that method.

    if you want to be able to use that variable outside that method as well, you'll have two options:

    Return the variable:

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

    or make an out parameter for that variable (which I'd certainly not prefer in this case)

        public static void OFDMethod(out string selectedFilename)
        {
           using( var ofd = new OpenFileDialog() )
           {   
               ofd.Filter = "Image files|*.jpg;*.jpeg;*.png;*.gif";
               if( ofd.ShowDialog() == DialogResult.OK )
               {
                   selectedFilename = ofd.Filename;
               }
               else
               {
                    selectedFilename = string.Empty;
               }
           }
        }
    

提交回复
热议问题