簡體   English   中英

如何在多個實例中維護對象 - C#

[英]How to maintain object in multiple instances - C#

我在 MainWindow 類中維護一個對象(父)。 該父對象正在傳遞給另一個對象(objMyClass)。 現在如果我在主窗口中更新父對象,它不會在 objMyClass 對象中反映它。 下面是代碼。

using System.Windows;

namespace WpfApp2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public Parent objParent;
        public MyClass objMyClass;

        public MainWindow()
        {
            InitializeComponent();
            objParent = new Parent();
            objMyClass = new MyClass(objParent);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if ((bool)checkPWB.IsChecked)
                objParent = new Child1();
            else
                objParent = new Child2();

            objParent.Display();
            objMyClass.par.Display();
        }
    }

    public class MyClass
    {
        public Parent par;

        public MyClass(Parent p)
        {
            par = p;
        }

    }

    public class Parent
    {
        public virtual void Display()
        {
            MessageBox.Show("I am Parent");
        }
    }

    public class Child1 : Parent
    {
        public override void Display()
        {
            MessageBox.Show("I am Child1");
        }
    }

    public class Child2 : Parent
    {
        public override void Display()
        {
            MessageBox.Show("I am Child2");
        }
    }
}

當我單擊按鈕時,我正在創建一個新對象 (Child1) 並分配給我的父對象,該對象未在 ObjectMyClass 中反映出來。

對此的任何幫助表示贊賞。

要引用相同的字段,您可以使用Func<Parent>來返回當前字段的值:

public class MyClass
{
    private Func<Parent> getParent = null;
    public Parent par => getParent();

    public MyClass(Func<Parent> getParent)
    {
        this.getParent = getParent;
    }
}

並將您的課程構建為

objMyClass = new MyClass(() => objParent);  

通過這種方式,而不是擁有自己對包含參數原始值副本的Parent對象的引用(如問題中的代碼),此MyClass將始終返回objParent字段的當前值,並確實反映對該字段的更改。

或者,您可以直接更改par屬性而不是更改objParent

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM