C#使用反射获取参数的值

编程入门 行业动态 更新时间:2024-10-24 10:16:29
本文介绍了C#使用反射获取参数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何获取参数的值(在使用反射的循环中).在上一个问题中,有人向我展示了如何使用反射循环遍历参数.

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#使用反射获取参数的值

本文发布于:2023-11-11 18:34:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579244.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:反射   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!