在 Xamarin Forms 中使用 Prism 在 ContentPages 之间导航维护 NavigationParameters

Navigating between ContentPages with Prism in Xamarin Forms maintains NavigationParameters

使用 Prism 中的 NavigationParameters 集合,我们将一个对象从一个 ContentPage 传递到另一个显示为模态的 ContentPage。

模态允许用户编辑数据。如果用户决定取消编辑表单,我们调用:

NavigationService.GoBackAsync(null, true). 

导航回上一页后,传递给模式的原始 属性 已使用编辑后的值更新,但未进行设置。

NavigationParameters 是否在 NavigateAsync 中作为引用传递?防止这种情况发生的最佳方法是什么?

Using the NavigationParameters collection within Prism, we are passing an object [...] [Emphasis mine]

您正在 NavigationParameters 中设置一个对象。 classes(对象)的实例在 C# 中通过引用传递,结构实例通过值传递。对于结构,有语义来复制和比较值(即所有 public 属性分别被复制和比较),但对于 classes 没有类似的语义。

请参阅documentation:

Because classes are reference types, a variable of a class object holds a reference to the address of the object on the managed heap. If a second object of the same type is assigned to the first object, then both variables refer to the object at that address.

为了防止原始对象被更新,你必须在对象被操作之前复制对象(我会在传递它之前复制它,但你可以也将其复制到目标站点)。如果您的 class 仅包含值类型属性,则浅拷贝就足够了,即您创建一个方法(或 属性,但这可能会产生误导)returns 您的 class 复制所有值

class MyClass
{
    int Value1 { get; set; }
    float Value2 { get; set; }

    public MyClass Copy()
    {
        var copy = new MyClass()
                       {
                           Value1 = this.Value1,
                           Value2 = this.Value2
                       }
        return copy;
    }
}

如果您的对象本身包含引用类型,您可能必须创建深拷贝

class MyClass
{
    MyClass2 Reference { get; set; }

    public MyClass Copy()
    {
        var copy = new MyClass()
                       {
                           Reference = this.Reference.Copy()
                       }
        return copy;
    }
}

当然,那些也必须实现 Copy() 方法。