Get-Set被按钮访问时返回null

本文关键字:返回 null 访问 按钮 Get-Set | 更新日期: 2023-09-27 17:52:43

我可能错过了一些简单的东西,但已经搞乱了这个几个小时,我不能得到的方法返回的东西不是null。当我跳过这个过程时,getDir1将获取类"swSheetFormatCycle.Form1"的值。文件夹更新",但getDir1。SwDir仍然为空,所以SwDir仍然为空。按钮方法不会像我这样设置swDir或swTemplate吗?

   // Get-Set Class
public class FolderUpdate
{
    private string swDir;
    public string SwDir
    {
        get {return swDir;}
        set {swDir = value;}
    }
    private string swTemplate;
    public string SwTemplate
    {
        get {return swTemplate;}
        set {swTemplate = value;}
    }
}
private void btnTemBrow_Click(object sender, EventArgs e)
{
    OpenFileDialog tempBrowse = new OpenFileDialog();
    DialogResult result = tempBrowse.ShowDialog();
    string tempText = tempBrowse.FileName;
    txtTemp.Text = tempText;
    // Setting the template field
    FolderUpdate temUpd = new FolderUpdate();
    temUpd.SwTemplate = tempText;
}
private void btnDirBrow_Click(object sender, EventArgs e)
{
    FolderBrowserDialog dirBrowse = new FolderBrowserDialog();
    DialogResult result = dirBrowse.ShowDialog();
    string dirText = dirBrowse.SelectedPath;
    txtDir.Text = dirText;
    // Setting the directory field
    FolderUpdate dirUpd = new FolderUpdate();
    dirUpd.SwDir = dirText;
}
// Get the directory set by the button method
swSheetFormatCycle.Form1.FolderUpdate getDir1 = new swSheetFormatCycle.Form1.FolderUpdate();
string swDir = getDir1.SwDir;
// Get the template set by the button method
swSheetFormatCycle.Form1.FolderUpdate getDir2 = new swSheetFormatCycle.Form1.FolderUpdate();
string swTemplate = getDir2.SwTemplate;

Get-Set被按钮访问时返回null

您的按钮事件正在创建您的FolderUpdate类的新实例,然后不对该对象做任何事情,并且在方法调用结束时放弃。

你的"//获取按钮方法设置的目录"代码还创建了新的实例,因此它们也将为空

将FolderUpdate实例附加到表单本身,以便您可以引用它。

public class FolderUpdate
{
    .... 
}

public FolderUpdate Folders { get; set; }
private void btnTemBrow_Click(object sender, EventArgs e)
{
     ...
     Folders.SwTemplate = tempText;
}
private void btnDirBrow_Click(object sender, EventArgs e)
{
     ...
     Folders.SwDir = dirText;
}

// Then when you are reading them
var folders = swSheetFormatCycle.Form1.Folders;
string swDir = folders.SwDir;
string swTemplate = folders.SwTemplate;