【C#】泛型约束练习题:用泛型实现一个单例模式

练习题:用泛型实现一个单例模式。

namespace 泛型约束
{
    //练习题:
    //用泛型实现一个单例模式
    //单例模式是指确保一个类只有一个实例,并提供一个全局访问点。
    public class Singleton<T> where T: Singleton<T>, new()
    {
        //static允许类名.访问
        private static T _instance = null;

        /// <summary>
        /// 通过属性得到Singleton类型的实例
        /// </summary>
        public static T GetSingleton
        {
            //有get无set,为属性只读
            get 
            {
                if (_instance == null) { _instance = new T(); }
                return _instance;
            }
        }
    }

    public class Singleton1<T> where T : Singleton1<T>, new()
    {
        //static允许类名.访问
        private static T _instance = null;

        /// <summary>
        /// 通过方法得到Singleton类型的实例
        /// </summary>
        public static T GetSingleton1()
        {
            if (_instance == null) { _instance = new T(); }
            return _instance;
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值