国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > 綜合 > 正文

C#2.0中用范型實(shí)現(xiàn)單例模式

2024-07-21 02:17:52
字體:
供稿:網(wǎng)友

 

#region using directives

using system;
using system.collections.generic;
using system.text;
using system.reflection;

#endregion

namespace genericssingleton
{
    /// <summary>
    /// 單例范型
    /// </summary>
    /// <typeparam name="t"></typeparam>
    public class singleton<t>
    {
        private static t _instance;

        public singleton()
        {
        }

        public static t instance
        {
            get
            {
                if (_instance == null)
                {  

                   //獲得實(shí)例,使用這個方法的前提是t要有公有的、無參數(shù)的構(gòu)造函數(shù)               

                   _instance = (t)system.activator.createinstance(typeof(t));
                }
                return _instance;
            }
        }
    }

    /// <summary>
    /// 要實(shí)現(xiàn)單例的類
    /// </summary>
    public class foo
    {
        private int count = 0;

        public int count
        {
            get
            {
                count++;
                return count;
            }
        }
    }

    /// <summary>
    /// 主函數(shù)
    /// </summary>
    class program
    {
        static void main(string[] args)
        {
            //連續(xù)調(diào)用三次如果值是遞增的話說明三次調(diào)用都是同一個實(shí)例
            console.writeline(singleton<foo>.instance.count);
            console.writeline(singleton<foo>.instance.count);
            console.writeline(singleton<foo>.instance.count);

            console.readline();
        }
    }
}


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 潞西市| 嘉鱼县| 临沧市| 罗山县| 石门县| 常德市| 资源县| 开原市| 资阳市| 调兵山市| 新田县| 日喀则市| 扎赉特旗| 喜德县| 仪陇县| 谷城县| 济阳县| 于都县| 桦南县| 会宁县| 定安县| 山西省| 资阳市| 海原县| 武乡县| 海门市| 大悟县| 建德市| 新邵县| 搜索| 双鸭山市| 曲周县| 东阳市| 贵溪市| 卢龙县| 涟源市| 京山县| 神农架林区| 榕江县| 资阳市| 长垣县|