以某种方式避免公共构造函数C#

时间:2014-02-24 22:06:08

标签: c#

我刚刚创建了某种通用存储库,它似乎正在工作,我唯一的问题是,是否有任何解决方案可以避免在类中使用公共构造函数,哪些必须实例化到存储库?

我的代码在这里:

public sealed class repository
{
    private static readonly object _lock = new object();

    private static readonly object _syncroot = new object();

    private static volatile repository _instance;

    private static readonly Dictionary<int, object> _dict
        = new Dictionary<int, object>();

    private repository()
    {
    }

    public static repository instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null) _instance = new repository();
                }
            }
            return _instance;
        }
    }

    public void allocate<Tc>(int id, object constructor_param) where Tc : Irepository<Tc>, new()
    {
        lock (_syncroot)
        {
            if (!_dict.ContainsKey(id))
            {
                var n = new Tc();
                _dict.Add(id, n.New(constructor_param));
            }
        }
    }

    public T get<T>(int id)
    {
        lock (_syncroot)
        {
            return (T) _dict[id];
        }
    }
}

public interface Irepository<out T>
{
    T New(object constructor_param);
}

public class RpSupportedClass : Irepository<RpSupportedClass>
{
    public object _constructor_param;

    private RpSupportedClass(object constructor_param)
    {
        _constructor_param = constructor_param;
    }

    public RpSupportedClass()
    {
    }

    public RpSupportedClass New(object constructor_param)
    {
        return new RpSupportedClass(constructor_param);
    }
}

所以问题是我必须创建一个默认的公共构造函数:

    public RpSupportedClass()
    {
    }

...因为类型参数。我通过这种方式需要类型参数因为我想在类实例化时使用参数。

有什么出路吗?

谢谢!

0 个答案:

没有答案