小编edw*_*uck的帖子

具有静态注册的工厂模式

我在尝试使用静态构造函数通过以下工厂注册我的类型时遇到问题:

 public class Factory<T>
{
    public static Factory<T> Instance { get { return _instance; } }

    private static Factory<T> _instance = new Factory<T>();
    private Factory() { }
    static Factory() { }

    static Dictionary<string, Type> _registeredType = new Dictionary<string, Type>();

    public void Register(string id, T obj)
    {
        if (obj.GetType().IsAbstract || obj.GetType().IsInterface)
            throw new ArgumentException("Cannot create instance of interface or abstract class");

        _registeredType.Add(id, obj.GetType());
    }

    public T Create(string id, params object[] parameters)
    {
        Type type;

        if(!_registeredType.TryGetValue(id, out type))
            throw new UnsupportedShapeException(id);

        return …
Run Code Online (Sandbox Code Playgroud)

c# factory static-constructor

3
推荐指数
1
解决办法
7777
查看次数

标签 统计

c# ×1

factory ×1

static-constructor ×1