Programmatic equivalent of default(Type)

前端 未结 14 1506
时光取名叫无心
时光取名叫无心 2020-11-22 05:28

I\'m using reflection to loop through a Type\'s properties and set certain types to their default. Now, I could do a switch on the type and set the defau

14条回答
  •  伪装坚强ぢ
    2020-11-22 06:25

    If you're using .NET 4.0 or above and you want a programmatic version that isn't a codification of rules defined outside of code, you can create an Expression, compile and run it on-the-fly.

    The following extension method will take a Type and get the value returned from default(T) through the Default method on the Expression class:

    public static T GetDefaultValue()
    {
        // We want an Func which returns the default.
        // Create that expression here.
        Expression> e = Expression.Lambda>(
            // The default value, always get what the *code* tells us.
            Expression.Default(typeof(T))
        );
    
        // Compile and return the value.
        return e.Compile()();
    }
    
    public static object GetDefaultValue(this Type type)
    {
        // Validate parameters.
        if (type == null) throw new ArgumentNullException("type");
    
        // We want an Func which returns the default.
        // Create that expression here.
        Expression> e = Expression.Lambda>(
            // Have to convert to object.
            Expression.Convert(
                // The default value, always get what the *code* tells us.
                Expression.Default(type), typeof(object)
            )
        );
    
        // Compile and return the value.
        return e.Compile()();
    }
    
    
    

    You should also cache the above value based on the Type, but be aware if you're calling this for a large number of Type instances, and don't use it constantly, the memory consumed by the cache might outweigh the benefits.

    提交回复
    热议问题