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

前端 未结 5 899
没有蜡笔的小新
没有蜡笔的小新 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 05:53

    Here is a full working example based on @JonSkeet answer:

    using System;
    using System.Collections.Generic;
    
    namespace GenericProxy
    {
        class Program
        {
            static void Main()
            {
                GenericProxy proxy = new GenericProxy(ClientBase.Factory, "cream");
    
                Console.WriteLine(proxy.Proxy.ConfigName); // test to see it working
            }
        }
    
        public class ClientBase
        {
            static public ClientBase Factory(string configName)
            {
                return new ClientBase(configName);
            }
    
            // default constructor as required by new() constraint
            public ClientBase() { }
    
            // constructor that takes arguments
            public ClientBase(string configName) { _configName = configName; }
    
            // simple method to demonstrate working example
            public string ConfigName
            {
                get { return "ice " + _configName; }
            }
    
            private string _configName;
        }
    
        public class GenericProxy
            where T : ClientBase, new()
        {
            public GenericProxy(Func factory, string configName)
            {
                Proxy = factory(configName);
            }
    
            public T Proxy { get; private set; }
        }
    }
    

    Expect to see the following output: ice cream

提交回复
热议问题