C # The first Singleton mode,

Source: Internet
Author: User

C # The first Singleton mode,
When we use QQ, we will find that he can start multiple QQ, but sometimes, we don't want to do this, at this time we need to use the singleton mode. 1. convert the Form2 constructor to private

Using System. Windows. Forms; namespace Singleton mode {public partial class Form2: Form {private Form2 () {InitializeComponent ();}}}

2. Provide a static method to return an object

Using System. windows. forms; namespace Singleton mode {public partial class Form2: Form {private Form2 () {InitializeComponent ();} public static Form2 GetSingle () {Form2 form = new Form2 (); return form ;}}}

3. Call in Form1

Using System; using System. windows. forms; namespace Singleton mode {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void button#click (object sender, EventArgs e) {Form2 form = Form2.GetSingle (); // new Form2 (); form. show ();}}}

4. Create a singleton in Form2

Using System. windows. forms; namespace Singleton mode {public partial class Form2: Form {// globally unique Singleton public static Form2 FrmSingle = null; // This is a static field, the initial value is set to null private Form2 () {InitializeComponent ();} public static Form2 GetSingle () {if (FrmSingle = null) // make a judgment, if FrmSingle is null, {FrmSingle = new Form2 () is created; // after this object is created, Form2 is not given, and FrmSingle} return FrmSingle; // return FrmSingle }}}

After completing the above steps, run Form1, regardless of the number of creation buttons, it is only the object created.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.