How do I get default values of optional parameters?

[亡魂溺海] 提交于 2019-12-10 11:28:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!