如何获取parms的值(使用反射循环).在之前的问题中,有人向我展示了如何使用反射来遍历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反映所有方法参数
谢谢大家 - 似乎在Python,PERL,PHP中这很容易.
即使它可能不是反射,如果我使用反射来获取字段名称,似乎有一种简单的动态方式来获取基于名称的值.我还没有尝试过AOP(Aspect Oriented Programming)解决方案.如果我不能在一两个小时内做到这一点,我可能不会这样做.
Luk*_*keH 36
您可以通过在方法中创建匿名类型并利用投影初始化器来解决此问题.然后,您可以使用反射查询匿名类型的属性.例如:
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));
    }
}