Passing Object from Form to Form

后端 未结 3 1298
孤街浪徒
孤街浪徒 2021-01-29 03:04

I have a fairly large CRUD winform app that is set up to display forms embedded in tabcontrols. I want to have objects for Person,(has a) Enrollment,(has a) Plan that hold and

3条回答
  •  暖寄归人
    2021-01-29 03:42

    a) Singleton

    A global static property is not such a good idea from the code reuse perspective. If you are planning to access a global static property from all over your code, you are making your code pretty tied to this specific application.

    If there was always only a single instance of Person in your code, then you could place this Singleton inside the Person class, but certainly not inside your Program class. Note, however, that use of Singleton classes will usually be limited to logging service or something which is so widely common that it will surely never change.

    b) Same object reference

    In this case you don't need a singleton instance, but rather to pass the same reference to your data object (Person, or whatever it is) to each Form that is accessing it. If your Form is a representation of a part of your data, then you can pass only that part of data to the form, preferably through a simplest possible interface.

    Changing the data in one form will probably need to update other forms. That is what Model-View-Controller and similar patterns help you accomplish - notifying views that the data has been changed somewhere else.

    For example, by implementing the IPropertyNameChanged interface in your Person class, you can notify anyone interested (any Form), whenever a property is changed. Check this for an example: http://msdn.microsoft.com/en-us/library/ms229614.aspx. By attaching an event handler to that event in each form, you will notify all of them that they need to be invalidated.

提交回复
热议问题