首页 新闻 会员 周边

C# 单例模式的工厂类怎么写呢?

0
悬赏园豆:5 [已解决问题] 解决于 2013-05-05 11:37

我像下边这样写不对了,把代码放上来,高手帮我看看怎么改,很简短的代码。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CMD
{
    class SingleInstanceFactory<T>
    {
        public static T t;
        private void SingleInstanceFactory(){}
        public static T CreateInstance()
        {
            if (t == null)
            {
                t = new T();
            }
            return t;
        }
    }
}

编译都不通过,报的错如下 :

 

 

 

 

要怎么改才能完成这个功能呢?谢谢!

hexllo的主页 hexllo | 菜鸟二级 | 园豆:318
提问于:2013-05-03 17:34
< >
分享
最佳答案
0

不知道是LZ省略了还是就没有?我好像没看到 工厂产生自己单例的代码。

单例是产生自己,工厂还要有产生对象的方法,

你写的 CreateInstance是要产生单例么?是的话返回不该是SingleInstanceFactory么?咋是T。。。。,

而返回T的代码应该是工厂提供的方法,了解一下泛型约束, 加上where T : new()就行。

今天刚学的东西。。不知道理解对了么。。

 1         #region GetInstance
 2         private readonly OperationFactory getInstance = new OperationFactory();
 3         private OperationFactory()
 4         { }
 5 
 6         public OperationFactory GetInstance
 7         {
 8             get
 9             {
10                 return getInstance;
11             }
12         }
13         #endregion
收获园豆:3
北落师门α | 初学一级 |园豆:17 | 2013-05-04 02:21
其他回答(3)
0

t = (T)Activator.CreateInstance(typeof(T))

收获园豆:1
三阶 | 园豆:1436 (小虾三级) | 2013-05-03 17:49
0

亲可以了解一下泛型约束, 加上where T : new()

应该可以解决你的问题。

收获园豆:1
I,Robot | 园豆:9783 (大侠五级) | 2013-05-03 21:05
0

方法一:class SingleInstanceFactory<T> where T : new()

方法二:t = (T)Activator.CreateInstance(typeof(T))

楼主可以抽时间看一下泛型

墨猦 | 园豆:668 (小虾三级) | 2013-05-05 00:25
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册