如何获取 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 Reflection of all method parameters
谢谢大家 - 在 Python、PERL 和 PHP 中这似乎很容易。
即使它可能不是反射,但如果我使用反射来获取字段名称,似乎会有一种简单的动态方法来根据名称获取值。
我还没有尝试过 AOP (Aspect Oriented Programming) 的解决方案。
这是其中一件事,如果我不能在一两个小时内完成,我可能不会做。
最佳答案
您可以通过在您的方法中创建一个匿名类型并利用投影初始化器来解决这个问题。然后,您可以使用反射查询匿名类型的属性。例如:
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#使用反射获取params的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1867482/