How to constrain generic type to must have a construtor that takes certain parameters?

前端 未结 5 892
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 05:07

I have a wrapper generic class that intended to be used with a set of types. Those types are generated by a utility and are all derived from a base class ClientBase. While C

5条回答
  •  一向
    一向 (楼主)
    2020-12-03 06:01

    It's not possible. I'd like to see "static interfaces" to handle this, but don't expect them any time soon...

    Alternatives:

    • Specify a delegate to act as a factory for T
    • Specify another interface to act as a factory for T
    • Specify an interface on T itself for initialization (and add a constraint so that T implements the interface)

    The first two are really equivalent. Basically you'd change your proxy class to something like this:

    public class GenericProxy
        where T: ClientBase, new()
    {
        string _configName;
        T _proxy;
        Func _factory;
    
        public GenericProxy(Func factory, string configName)
        {
            _configName = configName;
            _factory = factory;
            RefreshProxy();
        }
    
        void RefreshProxy() // As an example; suppose we need to do this later too
        {
            _proxy = _factory(_configName);
        }
    }
    

    (I assume you're going to want to create more instances later - otherwise you might as well pass an instance of T into the constructor.)

提交回复
热议问题