问题描述
如何获取参数的值(在使用反射的循环中).在上一个问题中,有人向我展示了如何使用反射循环遍历参数.
How can I get the values of parms (in a loop using reflection). In previous question, someone showed me how to loop through the parms using reflection.
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 反射所有方法参数
If you must know why I want to do this, please see here: .NET Reflection of all method parameters
谢谢 - 似乎在 Python、PERL、PHP 中这很容易.
即使它可能不是反射,如果我使用反射来获取字段名称,似乎会有一种简单的动态方法来获取基于名称的值.我还没有尝试过 AOP(面向方面编程)的解决方案.这是如果我不能在一两个小时内完成的事情之一,我可能不会做.
Thanks all - it seems like in Python, PERL, PHP this would be easy.
Even though it may not be reflection, if I use reflection to get the field name, seems like there would be an easy dynamic way to get the value based on the name. I haven't tried AOP (Aspect Oriented Programming) the solutions yet. This is one of those things that if I can't do it in an hour or two, I probably won't do it.
推荐答案
你可以通过在你的方法中创建一个匿名类型并利用投影初始化器来解决这个问题.然后您可以使用反射查询匿名类型的属性.例如:
You can hack your way around this by creating an anonymous type inside your method and taking advantage of projection initialisers. You can then interrogate the anonymous type's properties using reflection. For example:
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));
}
}
这篇关于C#使用反射获取参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!