Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

C# Getting value of params using reflection

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));

    }
}

If you must know why I want to do this, please see here: .NET Reflection of all method parameters


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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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));
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...