是否有可能得到使用反射构造可选的参数值? [英] Is it possible to get the optional parameter values from a constructor using reflection?
本文介绍了是否有可能得到使用反射构造可选的参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于像这样的类:
public abstract class SomeClass
{
private string _name;
private int _someInt;
private int _anotherInt;
public SomeClass(string name, int someInt = 10, int anotherInt = 20)
{
_name = name;
_someInt = someInt;
_anotherInt = anotherInt;
}
}
是否有可能使用反射来获取可选参数的默认值?值
Is it possible using reflection to get the optional parameter's default values?
推荐答案
让我们一个基本程序:
class Program
{
static void Main(string[] args)
{
Foo();
}
public static void Foo(int i = 5)
{
Console.WriteLine("hi" +i);
}
}
和看一些IL代码。
有关富:
.method public hidebysig static void Foo([opt] int32 i) cil managed
{
.param [1] = int32(0x00000005)
// Code size 24 (0x18)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "hi"
IL_0006: ldarg.0
IL_0007: box [mscorlib]System.Int32
IL_000c: call string [mscorlib]System.String::Concat(object,
object)
IL_0011: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: nop
IL_0017: ret
} // end of method Program::Foo
有关主营:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 9 (0x9)
.maxstack 8
IL_0000: nop
IL_0001: ldc.i4.5
IL_0002: call void ConsoleApplication3.Program::Foo(int32)
IL_0007: nop
IL_0008: ret
} // end of method Program::Main
结束的注意,主要有5硬编码为调用的一部分,而在富的。调用方法实际上是硬编码是可选的值!该值是在两个呼叫站点和被调用网站。
Notice that main has 5 hardcoded as part of the call, and in Foo. The calling method is actually hardcoding the value that is optional! The value is at both the call-site and callee site.
您可以通过使用形式的可选值来获得:
typeof运算(SomeClass的).GetConstructor(新[] {typeof运算(字符串)的typeof(INT)的typeof(INT)})
.GetParameters()[1] .RawDefaultValue
在MSDN为默认值(在其他答复中提到):
On MSDN for DefaultValue (mentioned in the other answer):
的这个属性只用于执行上下文。在只反射上下文中,使用RawDefaultValue属性。 MSDN 的
和最后一个POC:
static void Main(string[] args)
{
var optionalParameterInformation = typeof(SomeClass).GetConstructor(new[] { typeof(string), typeof(int), typeof(int) })
.GetParameters().Select(p => new {p.Name, OptionalValue = p.RawDefaultValue});
foreach (var p in optionalParameterInformation)
Console.WriteLine(p.Name+":"+p.OptionalValue);
Console.ReadKey();
}
这篇关于是否有可能得到使用反射构造可选的参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文