在分配给参数的属性中保留引用

本文关键字:保留 引用 属性 分配 参数 | 更新日期: 2023-09-27 18:01:17

我正在组装一个向导,该向导具有向用户显示的多个页面。我需要一个页面,能够从用户选择上一页访问数据。我的想法是通过引用将参数传递到两个页面的构造函数中,然后为该参数分配属性,但更改不会在页面之间持续存在。我假设这意味着我错误地使用了ref。我不能直接将数据传递给方法本身,因为它们是由向导主机控制的。

主机初始化:

    WizardHost host = new WizardHost();
    using (host)
    {
        host.Text = Migration.Properties.Resources.AppName;
        host.ShowFirstButton = false;
        host.ShowLastButton = false;
        host.WizardCompleted += new WizardHost.WizardCompletedEventHandler(this.Host_WizardCompleted);
        Reference<DBManip> dbControllerRef = new Reference<DBManip>();
        bool exportPathActive = false;
        host.WizardPages.Add(1, new Page1());
        host.WizardPages.Add(2, new Page2(dbControllerRef));
        host.WizardPages.Add(3, new Page3(dbControllerRef, ref exportPathActive));
        host.WizardPages.Add(4, new Page4(dbControllerRef, ref exportPathActive));
        host.WizardPages.Add(5, new Page5());
        host.LoadWizard();
        host.ShowDialog();

ref被属性链接的页面:

    public Page3(Reference<DBManip> dbControllerRef, ref bool exportPathActive)
    {
        this.InitializeComponent();
        this.DBControllerRef = dbControllerRef;
        this.Page3Body.Text = Migration.Properties.Resources.Page3Body;
        this.ExportPathActiveRef = exportPathActive;
    }
    public Reference<DBManip> DBControllerRef
    {
        get;
        private set;
    }

如果我在构造函数中修改了exportPathActive,那么修改将保留在下一页,但是分配给传递参数的属性不会保留引用。我对c#很陌生,所以这可能是我错过的一些愚蠢的东西,但我在谷歌上找不到它或四处寻找so .

在分配给参数的属性中保留引用

我决定只做一个名为PersistentData的类,带有一个名为ExportPathActive的属性,然后传递它。它工作得很好,如果需要,我可以扩展它以容纳更多的数据。我将等待批准,以防有更优雅的方法发布。

类:

/// <summary>
/// A store to pass data between pages.
/// </summary>
public class PersistentData
{
    /// <summary>
    /// Initializes a new instance of the <see cref="PersistentData"/> class.
    /// </summary>
    public PersistentData()
    {
        this.ExportPathActive = false;
    }
    /// <summary>
    /// Gets or sets a value indicating whether [export path active].
    /// </summary>
    /// <value>
    ///   <c>true</c> if [export path active]; otherwise, <c>false</c>.
    /// </value>
    public bool ExportPathActive { get; set; }
}