In C#, how to instantiate a passed generic type inside a method?

前端 未结 8 1020
逝去的感伤
逝去的感伤 2020-11-30 21:19

How can I instantiate the type T inside my InstantiateType method below?

I\'m getting the error: \'T\' is a \'type parameter\' but is u

相关标签:
8条回答
  • 2020-11-30 21:37

    Couple of ways.

    Without specifying the type must have a constructor:

    T obj = default(T); //which will produce null for reference types
    

    With a constructor:

    T obj = new T();
    

    But this requires the clause:

    where T : new()
    
    0 讨论(0)
  • 2020-11-30 21:48

    A bit old but for others looking for a solution, perhaps this could be of interest: http://daniel.wertheim.se/2011/12/29/c-generic-factory-with-support-for-private-constructors/

    Two solutions. One using Activator and one using Compiled Lambdas.

    //Person has private ctor
    var person = Factory<Person>.Create(p => p.Name = "Daniel");
    
    public static class Factory<T> where T : class 
    {
        private static readonly Func<T> FactoryFn;
    
        static Factory()
        {
            //FactoryFn = CreateUsingActivator();
    
            FactoryFn = CreateUsingLambdas();
        }
    
        private static Func<T> CreateUsingActivator()
        {
            var type = typeof(T);
    
            Func<T> f = () => Activator.CreateInstance(type, true) as T;
    
            return f;
        }
    
        private static Func<T> CreateUsingLambdas()
        {
            var type = typeof(T);
    
            var ctor = type.GetConstructor(
                BindingFlags.Instance | BindingFlags.CreateInstance |
                BindingFlags.NonPublic,
                null, new Type[] { }, null);
    
            var ctorExpression = Expression.New(ctor);
            return Expression.Lambda<Func<T>>(ctorExpression).Compile();
        }
    
        public static T Create(Action<T> init)
        {
            var instance = FactoryFn();
    
            init(instance);
    
            return instance;
        }
    }
    
    0 讨论(0)
提交回复
热议问题