2012-07-11 85 views
1

我正在使用VS 2008(C#)...我在GlobalClass中創建了一個函數來全局使用它..這是打開一個對話框。當我打電話在我的方法這種功能,它的工作原理,但我不能使用,我已經在這裏創建的對象「OFD」 ......如何在方法外部使用在方法中聲明的變量?

static class GlobalClass 
{ 
public static void OFDbutton() 
    { 
    OpenFileDialog ofd = new OpenFileDialog(); 
    ofd.Filter = "Image files|*.jpg;*.jpeg;*.png;*.gif"; 
    DialogResult dr = ofd.ShowDialog(); 
    } 
} 

在形式方法。我使用

globalclass.ofdbutton(); //Calling the function 
lable1.text=ofd.filename; 

我想使用對象「OFD」但我不能這樣做。什麼我必須做這個,請幫助

回答

1

我想你想要的是

static class GlobalClass 
{ 
public static OpenFileDialog OFDbutton() 
    { 
    OpenFileDialog ofd = new OpenFileDialog(); 
    ofd.Filter = "Image files|*.jpg;*.jpeg;*.png;*.gif"; 
    DialogResult dr = ofd.ShowDialog(); 
    return ofd; 
    } 
} 

這給後面的OpenFileDialog對象。現在你可以

OpenFileDialog ofd = globalclass.ofdbutton(); //Calling the function 
label1.text=ofd.filename; 
+0

謝謝,我正在尋找這個....我正在返回thed,但我使用的返回類型是字符串,這就是爲什麼我無法使用該對象。我需要的對象「ofd」作爲一個整體不是獨自ofd.filename根據我的項目要求........ – Jain 2012-07-11 14:16:47

+0

@Jain您顯示的代碼只使用of.Filename,這就是爲什麼大多數人回答只是ofd 。文件名。你永遠不應該回報超過你的需要。目前尚不清楚您需要更多,但您最好找到適合您的解決方案。 =) – 2012-07-12 08:29:41

4

您可能要返工的方法以實際返回文件名。

喜歡的東西

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

當然,這是一個非常幼稚的做法,你可能想要的變量範圍念起來和一般的面向對象的設計。

編輯:This answer擴展此問題並改進設計,同時考慮到用戶可能在對話框本身中單擊取消。

Edit2:無恥地從鏈接的答案複製,我修改我自己的片段。

2

當你在一個方法中聲明一個變量時,那麼這個變量的作用域就是該方法。

,如果你希望能夠使用該方法之外的變量,以及,你有兩種選擇:

返回變量:

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

或進行了參數變量(這我肯定不會在這種情況下喜歡)

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

要麼改變該方法返回的文件名或對話框對象本身 或移動OPENFILE對話進入方法

0

之外的獨立財產做這樣的 -

static class GlobalClass 
{ 
    public static string OFDbutton() 
    { 
     OpenFileDialog ofd = new OpenFileDialog(); 
     ofd.Filter = "Image files|*.jpg;*.jpeg;*.png;*.gif"; 
     DialogResult dr = ofd.ShowDialog(); 
     return ofd.FileName; 
    } 
} 

lable1.text = GlobalClass.OFDbutton(); 
0

如何使用在方法中聲明的變量,這個方法麼?

你不行。您可以將聲明移到方法外部。然後它變成包含類的字段

但是很多人都說過,在這種情況下,最好使用return這個文件名。

方法「展現」到外部世界的唯一方法是參數(它可能會改變它們所引用的對象;或者如果它們是refout,則會分配給它們)和返回值。

相關問題