C#使用反射获取Parms的价值 [英] C# Getting value of parms using reflection

查看:69
本文介绍了C#使用反射获取Parms的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取parms的值(使用反射的循环中)。
在上一个问题中,有人向我展示了如何使用反射遍历这些parm。

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#使用反射获取Parms的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆