问题
I have a constructor with optional parameters. I would like to have an expression to invoke that constructor without providing the optional arguments (I mean let the object be constructed with default values of the parameters).
I read here An expression tree may not contain a call or invocation that uses optional arguments that this is not possible.
I mean
var ctorInfo = getIt;
var f = Expression.Lambda<Func<T>>(Expression.New(ctorInfo)).Compile();
fails with System.TypeInitializationException
.
Alright, I will pass the default values. But how do I get the default values of the parameters?
ctorInfo.GetParameters().Select(??
Motive: Learning purpose, no real world application.
Edit: Edited out expression-tree tag since its not in the context of building expressions, valid in general too.
回答1:
According to the documentation for ParameterInfo.RawDefaultValue:
ctorInfo.GetParameters().Select( p => p.RawDefaultValue );
Hope it helps
EDIT: Corrected property because:
This property [DefaultValue] is used only in the execution context. In the reflection-only context, use the RawDefaultValue property instead.
来源:https://stackoverflow.com/questions/16185124/how-do-i-get-default-values-of-optional-parameters