Is there a way to get an array of the arguments passed to a method?

后端 未结 9 1258
小蘑菇
小蘑菇 2020-12-05 18:17

Say I have a method:

 public void SomeMethod(String p1, String p2, int p3)
 {

 #if DEBUG
    object[] args = GetArguments();
    LogParamaters(args);
 #endi         


        
9条回答
  •  有刺的猬
    2020-12-05 18:27

    I am unsure if the API to access the call stack provides a means to get the argument list.

    However there are ways to inject IL to intercept method calls and execute custom code.

    The Library I use frequently is PostSharp by Gael Fraiteur, it includes an application that runs postbuild and injects IL in your output assemblies depending on the Aspects that you are using. There are attributes with which you can decorate assemblies, types, or individual methods. For instance:

    [Serializable]
    public sealed class LoggingAttribute : OnMethodBoundaryAspect
    {
        public override void OnEntry(MethodExecutionArgs eventArgs)
        {
            Console.WriteLine("Entering {0} {1} {2}",
                              eventArgs.Method.ReflectedType.Name,
                              eventArgs.Method,
                              string.Join(", ", eventArgs.Arguments.ToArray()));
    
            eventArgs.MethodExecutionTag = DateTime.Now.Ticks;
        }
    
        public override void OnExit(MethodExecutionArgs eventArgs)
        {
            long elapsedTicks = DateTime.Now.Ticks - (long) eventArgs.MethodExecutionTag;
            TimeSpan ts = TimeSpan.FromTicks(elapsedTicks);
    
            Console.WriteLine("Leaving {0} {1} after {2}ms",
                              eventArgs.Method.ReflectedType.Name,
                              eventArgs.Method,
                              ts.TotalMilliseconds);
        }
    }
    

    After this you can just decorate the method you want with this Attribute:

    [Logging]
    public void SomeMethod(String p1, String p2, int p3) 
    {
       //..
    }
    

提交回复
热议问题