Using C #2.0 generics makes it possible to implement what I call "Singleton provider. This is a single-class instance that can be created. You do not need to override the singleton mode for each specific class. Code Class. In this way, separating the code of the singleton structure will help to maintain the flexibility of using classes in singleton mode or not in singleton mode.
/// <Summary>
/// Singleton provider
/// </Summary>
/// <Typeparam name = "T"> required class </typeparam>
Public class singletonprovider <t> where T: New ()
{
Singletonprovider (){}
Public static t instance
{
Get {return singletoncreator. instance ;}
}
Class singletoncreator
{
Static singletoncreator (){}
Internal static readonly t instance = new T ();
}
}
Where keyword (msdn)
When defining generic classes, you can impose restrictions on the types of types that client code can use for type parameters when instantiating classes. If the client code attempts to instantiate a class using a type not allowed by a certain constraint, a compile-time error will occur. These restrictions are called constraints. The constraint is to useWhereSpecified by the context keyword. The following table lists five types of constraints:
& Lt; table width = "100%" & gt;
| constraint |
description |
| T: Structure |
the type parameter must be a value type. You can specify any value type except nullable. |
| T: class |
the type parameter must be of the reference type, including any class, interface, delegate, or array type. |
| T: New () |
type parameters must have a public constructor without parameters. When used with other constraints, the New () constraint must be specified at the end. |
| T: |
the type parameter must be a specified base class or derived from the specified base class. |
| T: |
the type parameter must be a specified interface or implement a specified interface. Multiple interface constraints can be specified. The constraint interface can also be generic. |
| T: U |
type parameters provided for T must be provided for U or derived from U. This is called the bare type constraint. |