标签:admin 实例 rgs int blog sync 静态方法 main 场景
对于泛型类,我们一定十分熟悉了。比如:List
泛型类型的声明,在C#:泛型中已经提及,但是并未给出一个实际工作中应用的示例;
class SingleTonBase<T> where T : class
{
private static T _instance;
public static readonly object SyncObject = new object();
public static T GetInstance()
{
if (_instance == null)//为了防止每次都要获取锁,增加程序耗时
{
lock (SyncObject)//同步锁,防止实例被同时访问
{
if (_instance == null)
{
_instance = (T) Activator.CreateInstance(typeof(T), true);
}
}
}
return _instance;
}
public static void SetInstance(T value)
{
_instance = value;
}
}
使用方式:
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Thread thread=new Thread(new ThreadStart(TestSingleton));
thread.Start();
}
Console.ReadLine();
}
static void TestSingleton()
{
Student student = SingleTonBase<Student>.GetInstance();
Console.WriteLine($"{student.GetHashCode()}:{student.StudentName},{student.StudentAge}");
}
}
class Student
{
private Student()
{
StudentName = "admin";
StudentAge = 18;
Console.WriteLine("构造函数运行...");
}
public string StudentName { get; set; }
public int StudentAge { get; set; }
}
运行结果:
构造函数运行...
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
通过运行结果可以看出:通过泛型类型SingleTonBase
以上便是对泛型类型的知识总结,记录下来以便以后查看。
标签:admin 实例 rgs int blog sync 静态方法 main 场景
原文地址:https://www.cnblogs.com/bigbosscyb/p/14021255.html