如何获取 parms 的值(在使用反射的循环中)。
在上一个问题中,有人向我展示了如何使用反射循环参数。
static void Main(string[] args)
{
ManyParms("a","b","c",10,20,true,"end");
Console.ReadLine();
}
static void ManyParms(string a, string b, string c, int d, short e, bool f, string g)
{
var parameters = MethodBase.GetCurrentMethod().GetParameters();
foreach (ParameterInfo parameter in parameters)
{
string parmName = parameter.Name;
Console.WriteLine(parmName);
//Following idea required an object first
//Type t = this.GetType();
//t.GetField(parmName).GetValue(theObject));
}
}
如果您一定知道我为什么要这样做,请参阅此处:.NET 所有方法参数的反射 https://stackoverflow.com/questions/1862433/net-reflection-of-all-method-parameters
谢谢大家 - 看起来在 Python、PERL、PHP 中这很容易。
即使它可能不是反射,如果我使用反射来获取字段名称,似乎会有一种简单的动态方法来根据名称获取值。
我还没有尝试过AOP(面向方面编程)的解决方案。
这是如果我不能在一两个小时内完成的事情之一,我可能不会做。
您可以通过在方法内创建匿名类型并利用投影初始化程序来解决此问题。然后,您可以使用反射来询问匿名类型的属性。例如:
static void ManyParms(
string a, string b, string c, int d, short e, bool f, string g)
{
var hack = new { a, b, c, d, e, f, g };
foreach (PropertyInfo pi in hack.GetType().GetProperties())
{
Console.WriteLine("{0}: {1}", pi.Name, pi.GetValue(hack, null));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)