如何获取可选参数的默认值? [英] How do I get default values of optional parameters?

查看:145
本文介绍了如何获取可选参数的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可选参数的构造函数。 我想有一个表达来调用构造函数不提供可选的参数(我的意思是让物体带有参数的默认值构造)。

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.

我来电或调用意味着

var ctorInfo = getIt;
var f = Expression.Lambda<Func<T>>(Expression.New(ctorInfo)).Compile();



System.TypeInitializationException 失败。

好的,我将通过缺省值。但是,我怎么得到这些参数的默认值吗?

Alright, I will pass the default values. But how do I get the default values of the parameters?

ctorInfo.GetParameters().Select(??

动机:学习目的,没有实际的应用程序

编辑:编辑出的表达式树的标记,因为它不是在建筑表现,一般也有效的情况下

Edited out expression-tree tag since its not in the context of building expressions, valid in general too.

推荐答案

据的 的文档 ParameterInfo.RawDefaultValue

ctorInfo.GetParameters().Select( p => p.RawDefaultValue );

希望它能帮助

编辑:修正属性,因为:

Corrected property because:

这属性[默认值]仅用于在执行上下文。在
只反射上下文中,使用RawDefaultValue属性。

This property [DefaultValue] is used only in the execution context. In the reflection-only context, use the RawDefaultValue property instead.

这篇关于如何获取可选参数的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆