Most efficient way to get default constructor of a Type

后端 未结 5 1082
礼貌的吻别
礼貌的吻别 2021-02-02 05:00

What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type?

I was thinking something along the lines o

5条回答
  •  半阙折子戏
    2021-02-02 05:51

    If you have the generic type parameter, then Jeff Bridgman's answer is the best one. If you only have a Type object representing the type you want to construct, you could use Activator.CreateInstance(Type) like Alex Lyman suggested, but I have been told it is slow (I haven't profiled it personally though).

    However, if you find yourself constructing these objects very frequently, there is a more eloquent approach using dynamically compiled Linq Expressions:

    using System;
    using System.Linq.Expressions;
    
    public static class TypeHelper
    {
        public static Func CreateDefaultConstructor(Type type)
        {
            NewExpression newExp = Expression.New(type);
    
            // Create a new lambda expression with the NewExpression as the body.
            var lambda = Expression.Lambda>(newExp);
    
            // Compile our new lambda expression.
            return lambda.Compile();
        }
    }
    
    
    

    Just call the delegate returned to you. You should cache this delegate, because constantly recompiling Linq expressions can be expensive, but if you cache the delegate and reuse it each time, it can be very fast! I personally use a static lookup dictionary indexed by type. This function comes in handy when you are dealing with serialized objects where you may only know the Type information.

    NOTE: This can fail if the type is not constructable or does not have a default constructor!

    提交回复
    热议问题