获取参数名称

问题描述 投票:4回答:2

您如何获得方法的参数NAMES。这些示例说明如何获取参数的[[values,而不是NAMES。我想看到parma = 99,parmb =1。不只是99,1。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using PostSharp.Aspects; namespace GettingParmNames { public class Program { static void Main(string[] args) { Foo myfoo = new Foo(); int sum = myfoo.DoA(99, 1); Console.WriteLine(sum.ToString()); Console.ReadKey(); } } public class Foo { [ExceptionAspect] public int DoA(int parma, int parmb) { int retVal; try { retVal = parma + parmb; if (parma == 99) { throw new Exception("Fake Exception"); } } catch (Exception ex) { retVal = -1; throw new Exception("There was a problem"); } return retVal; } } [Serializable] public class ExceptionAspect : OnExceptionAspect { public override void OnException(MethodExecutionArgs args) { string parameterValues = ""; foreach (object arg in args.Arguments) { if (parameterValues.Length > 0) { parameterValues += ", "; } if (arg != null) { parameterValues += arg.ToString(); } else { parameterValues += "null"; } } Console.WriteLine("Exception {0} in {1}.{2} invoked with arguments {3}", args.Exception.GetType().Name, args.Method.DeclaringType.FullName, args.Method.Name, parameterValues ); } } }

如何获得方法的参数名称。这些示例向您展示了如何获取参数的值,而不是名称。我想看到parma = 99,parmb =1。不只是99,1.使用...
postsharp
2个回答
5
投票
您可以通过调用OnExceptionargs.Method.GetParameters()方法中访问方法参数的信息。但是通常出于性能原因,最好在编译时初始化数据-在CompileTimeInitialize方法覆盖中。

0
投票
AlexD的很好答案。
© www.soinside.com 2019 - 2024. All rights reserved.