如何从form.cs文件调用变量到program.cs文件

bob*_*mac 0 .net c# variables instance-variables

我无法访问我的两个变量.我在互联网上看了一下,发现我需要使用类似的东西form.dlg.selectedpath来调用它,但我得到了三个错误.有人说form.dlg无法访问,下一个说需要对象引用.我也尝试访问另一个,并说表单不包含dlg2的定义.

这是我想要变量的代码.

var di = new DirectoryInfo(Form1.dlg.SelectedPath);  
           di.CopyTo(Form1.dlg2.SelectedPath, true);
Run Code Online (Sandbox Code Playgroud)

这是我的代码我正在设置一个变量

 public partial class Form1 : Form    
    {  
        FolderBrowserDialog dlg = new FolderBrowserDialog();


        public Form1()
        {
            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {

            if (dlg.ShowDialog() == DialogResult.OK)
Run Code Online (Sandbox Code Playgroud)

第二个变量从这里引用.

private void button1_Click(object sender, EventArgs e)  
        {  
            FolderBrowserDialog dlg2 = new FolderBrowserDialog();  
            if (dlg2.ShowDialog() == DialogResult.OK)  
            //do whatever with dlg.SelectedPath  
            {  
                backgroundWorker1.RunWorkerAsync(dlg2.SelectedPath);  
            }  
        }  
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

Mar*_*ell 5

菲尔兹不应该直接暴露; 而是在表单上添加一个属性:

public string FolderPath {
    get { return dlg.SelectedPath; }
}
Run Code Online (Sandbox Code Playgroud)

然后从表单实例访问:

string path = myFormInstance.FolderPath;
Run Code Online (Sandbox Code Playgroud)

另外 - 确保dlg随表格处理; 在个人的协议中我根本不会把它作为一个字段 - 我有一个强大的字段,我在一个小块中分配,创建,使用和处理对话框:

public string FolderPath { get; private set; }

private void SelectPath() {
    using(var dlg = new FolderBrowserDialog()) { // or whatever type
        if(dlg.ShowDialog() == DialogResult.OK) {
            FolderPath = dlg.SelectedPath;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)