2013-03-16 100 views
0

我可以使用聲明變量或對象實例從一種方法到另一種嗎?我可以將一種方法的變量用於另一種方法嗎?

private void OnBrowseFileClick(object sender, RoutedEventArgs e) 
     { 
      string path = null; 
      path = OpenFile(); 
     } 

private string OpenFile() 
     { 
      string path = null; 
      OpenFileDialog fileDialog = new OpenFileDialog(); 
      fileDialog.Title = "Open source file"; 
      fileDialog.InitialDirectory = "c:\\"; 
      fileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; 
      fileDialog.FilterIndex = 2; 
      fileDialog.RestoreDirectory = true; 

      Nullable<bool> result = fileDialog.ShowDialog(); 

      if (result == true) 
      { 
       path = fileDialog.FileName; 
      } 

      textBox1.Text = path; 
      return path; 
     } 

現在,我想要獲得該路徑並將其寫入Excel。我將如何做到這一點,請大家幫忙,我在使用C#的時候已經一週了。

private void btnCreateReport_Click(object sender, RoutedEventArgs e) 
     { 
      string filename = "sample.xls"; //Dummy Data 
      string functionName = "functionName"; //Dummy Data 
      string path = null; 

      AnalyzerCore.ViewModel.ReportGeneratorVM reportGeneratorVM = new AnalyzerCore.ViewModel.ReportGeneratorVM(); 
      reportGeneratorVM.ReportGenerator(filename, functionName, path); 
     } 

感謝

回答

2

使用一個實例字段來存儲您的變量的值。

像這樣:

public class MyClass 
{ 
    // New instance field 
    private string _path = null; 

    private void OnBrowseFileClick(object sender, RoutedEventArgs e) 
    { 
     // Notice the use of the instance field 
     _path = OpenFile(); 
    } 

    // OpenFile implementation here... 

    private void btnCreateReport_Click(object sender, RoutedEventArgs e) 
    { 
     string filename = "st_NodataSet.xls"; //Dummy Data 
     string functionName = "functionName"; //Dummy Data 

     AnalyzerCore.ViewModel.ReportGeneratorVM reportGeneratorVM = new AnalyzerCore.ViewModel.ReportGeneratorVM(); 
     // Reuse the instance field here 
     reportGeneratorVM.ReportGenerator(filename, functionName, _path); 
    } 
} 

Here是描述更多的細節領域超過了我所能做的鏈接。

+0

謝謝Lukazoid ......這回答我的詢問。 :D – ichigo 2013-03-16 12:40:53

+0

嗨,是否有可能存儲一個函數返回在一個字符串中,並調用它的方法? 實施例是: 公共字符串FUNC = @「公衆詮釋添加(INT的x,int y)對 { INT Z者除外; 如果((X == 10)||(Y == 20)) { Z = X + Y; } 別的 { Z = X; } 返回Z者除外; }「; 而我想用一個方法調用並執行這個函數。謝謝 – ichigo 2013-03-18 04:09:47

-1

使用static private string path;

0

string path作爲類中的成員移動,並刪除方法內的聲明。應該這樣做

0

使用字符串路徑作爲類級別變量。

如果要在頁面之間使用靜態私有字符串路徑,請使用靜態私有字符串路徑。

如果您只需要在當前頁面上使用它,請使用私有字符串路徑。

0

你必須在你的類定義的變量場:

Private string path = null; 
相關問題