首先定义一个基类:
class Father<T> where T : new()
{
private static T instance = new T();
//属性
public static T Instance => instance;
}
其次定义一个子类继承这个基类:
class Son : Father<Son>
{
public int data;
}
这样就能轻松get值啦~
class Program
{
static void Main(string[] args)
{
Son.Instance.data = 10;
}
}
本文介绍了C#中使用泛型和new约束实现静态单例模式的方法,并通过一个Son类实例展示了如何在程序中获取并设置单例对象的属性。这种模式在保证性能的同时提供了类型安全。
941

被折叠的 条评论
为什么被折叠?



