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

谢谢

4

5 回答 5

3

使用实例字段来存储变量的值。

像这样:

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

是一个链接,它比我所能描述的更详细地描述了字段。

于 2013-03-16T12:27:04.337 回答
0

string path作为成员移动到您的类中,并删除方法中的声明。应该这样做

于 2013-03-16T12:27:42.120 回答
0

使用字符串路径作为类级别变量。

如果要在页面之间使用静态私有字符串路径,请使用它。

如果您只需要在当前页面上使用它,请使用私有字符串路径。

于 2013-03-16T12:27:53.100 回答
0

您必须将变量定义为类中的字段:

Private string path = null;
于 2013-03-16T12:28:39.740 回答
-1

采用static private string path;

于 2013-03-16T12:26:16.343 回答