简体   繁体   中英

How to maintain object in multiple instances - C#

I am maintaining one object(Parent) in my MainWindow class. That Parent Object is being passed to another object(objMyClass). Now If I update Parent Object in mainwindow, it is not reflecting it in objMyClass object. Below is the code.

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");
        }
    }
}

When I click the button, I am creating a new object (Child1) and assigning to my parent object which doesn't reflect it in ObjectMyClass.

Any help on this is appreciated.

To refer to the same field you can use Func<Parent> that would return current value of the filed:

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

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

and construct your class as

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

This way instead of having its own reference to Parent object that contains copy of the original value of the parameter (as in code in the question) this MyClass will always return current value of objParent field and indeed reflect changes to that field.

Alternatively you can just change par property directly instead of changing objParent .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM