2013-03-16 109 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; 
相关问题