A simple C # Generic Singleton class

Source: Internet
Author: User
Using System;
Using System. reflection;

Namespace Minicafe. util
{
/**/ ///   <Summary>
/// This is the base class for Singleton mode in CSHARP. derived class must have
/// Privae or protected constructor without any parameters, otherwise exception will
/// Be throwed.
///   </Summary>
///   <Typeparam name = "T"> </typeparam>

Public   Class Singleton < T >
Where t:
Class
{
Private   Static T instance;
/**/ /// <Summary>
///Instace property of class t
/// </Summary>

Public   Static T instance
{
Get
{
If (Instance =   Null )
{
Lock ( Typeof (T ))
{
If (Instance =   Null )
{
Constructorinfo Constructor
=   Typeof (T). getconstructor (bindingflags. Instance | Bindingflags. nonpublic, Null , New Type [ 0 ], New Parametermodifier [ 0 ]);
If (Constructor =   Null )
Throw   New Exception ( " The object that you want to singleton doesnt have a private/protected constructor so the property cannot be enforced. " );

Try
{< br> instance = constructor. invoke ( New Object [ 0 ]) as T;
}

Catch (Exception E)
{< br> throw New exception ( " the singleton couldnt be constructed, check if the type T has a default constructor " , e);
}

}

}

}

Return Instance;
}

}

}

}


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.