Difference between ParameterInfo.DefaultValue and ParameterInfo.RawDefaultValue

回眸只為那壹抹淺笑 提交于 2019-12-01 14:30:30

问题


This is a follow-up question of How do I get default values of optional parameters?

From documentation, DefaultValue:

Gets a value indicating the default value if the parameter has a default value.

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

The default value is used when an actual value is not specified in the method call. A parameter can have a default value that is null. This is distinct from the case where a default value is not defined.

From documentation, RawDefaultValue:

Gets a value indicating the default value if the parameter has a default value.

This property can be used in both the execution context and the reflection-only context.

The default value is used when an actual value is not specified in the method call. A parameter can have a default value that is null. This is distinct from the case where a default value is not defined.

The documentation is so similar except that one is for reflection context and other not. What difference is that? When is ever DefaultValue used without reflection at all? I mean how do we get a default value without reflection? Am I missing something?

Update

I created two overloads like this:

public void Required(string value)
{

}
public void Optional(string value = "", int i = -1)
{

}

I tested with:

var f = requiredInfo.GetParameters().Select(p => p.DefaultValue).ToArray();
var g = requiredInfo.GetParameters().Select(p => p.RawDefaultValue).ToArray();

var h = optionalInfo.GetParameters().Select(p => p.DefaultValue).ToArray();
var i = optionalInfo.GetParameters().Select(p => p.RawDefaultValue).ToArray();

//f equals g and h equals i in every way!

So what is the difference given that my test shows (all in reflection context) no difference at all?


回答1:


There is a subtle but significant difference between "in the context of reflection" and "the reflection-only context". The "reflection only context" is referring to something very specific:

  • How to: Load Assemblies into the Reflection-Only Context

It is a way to load an assembly for examination only and has the distinct advantage of not requiring any dependent assemblies to be loaded or even to be present.

Since you appear to have every intention of executing some of the code you are reflecting, the reflection-only context would be of limited use to you.



来源:https://stackoverflow.com/questions/16185826/difference-between-parameterinfo-defaultvalue-and-parameterinfo-rawdefaultvalue

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